Skip to content

Instantly share code, notes, and snippets.

@think49
Created May 11, 2011 09:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think49/966219 to your computer and use it in GitHub Desktop.
Save think49/966219 to your computer and use it in GitHub Desktop.
translate.js : XPath の translate() 関数。
/**
* translate-by-array.js
* translate function of XPath.
*
* @version 1.0.2
* @author think49
* @url https://gist.github.com/966219
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
* @see <a href="http://www.w3.org/TR/xpath/#function-translate">translate() - XML Path Language (XPath)</a>
*/
var translateByArray = (function (Object, String, Object_toString) {
function translateByArray (string, searchArray, replaceArray) {
var results, token, searchString, i, j, stringLength, arrayLength, tokenLength;
if (!isArray(searchArray)) {
return String(string);
}
replaceArray = Object(replaceArray);
arrayLength = searchArray.length;
i = replaceArray.length;
string = String(string);
results = [];
i = 0;
stringLength = string.length;
arrayLength = searchArray.length;
while (i < stringLength) {
token = string.charAt(0);
tokenLength = 1;
for (j = 0; j < arrayLength; ++j) {
searchString = searchArray[j];
if (string.indexOf(searchString, i) === i) {
token = replaceArray[j];
tokenLength = searchString.length;
break;
}
}
i += tokenLength;
results.push(token);
}
return results.join('');
}
var isArray = Array.isArray || function (arg) {
var type = typeof arg;
return arg !== null && type !== 'undefined' && type !== 'boolean' && type !== 'number' && type !== 'string' && Object_toString.call(arg) === '[object Array]';
};
return translateByArray;
})(Object, String, Object.prototype.toString);
/**
* translate.js
* translate function of XPath.
*
* @version 1.1.4
* @author think49
* @url https://gist.github.com/966219
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
* @see <a href="http://www.w3.org/TR/xpath/#function-translate">translate() - XML Path Language (XPath)</a>
*/
function translate (string, searchString, replaceString) {
var _String, i, len, index;
_String = String;
searchString = _String(searchString);
replaceString = _String(replaceString).split('');
len = searchString.length;
i = replaceString.length;
string = _String(string).split('');
i = string.length;
while (i--) {
index = searchString.indexOf(string[i]);
if (index !== -1) {
string[i] = replaceString[index];
}
}
return string.join('');
}