JavaScript是否有类似Ruby's tr
method的方法?
string.tr('0123456789','9876543210')
答案 0 :(得分:1)
这是我现在一起提出的实现方式
据我所知,它遵循ruby的实现
我不知道关于ruby实现的几件事
^
开始到to超过一个字符,那应该是一个错误吗?还是只使用第一个字符而忽略其余字符?如果该代码是字符串中的第一个或最后一个,则此代码仅使用破折号作为破折号,并且9-0
将变为9876543210
无论如何,希望这已经足够了
const tr = (str, from, to) => {
const fixupDash = s => {
const range = (l, h) => {
// let's assume a dash in the first or last position is a literal dash
if (typeof l !== 'string' || typeof h !== 'string') {
return l || h;
}
l = l.charCodeAt(0);
h = h.charCodeAt(0);
let sgn = Math.sign(h-l);
l += sgn;
h -= sgn;
return Array.from({length:Math.abs(h-l)+1}, (_, i) => String.fromCharCode(sgn * i + l)).join('');
}
return s.split('').map((c, i, a) => c === '-' ? range(a[i-1], a[i+1]) : c).join('');
}
from = fixupDash(from);
to = fixupDash(to).padEnd(from.length, to[to.length-1]);
if (from[0] !== '^') {
const mapper = Object.assign({}, ...from.split('').map((f, i) => ({[f]: to[i]})));
return str.split('').map(c => mapper.hasOwnProperty(c) ? mapper[c] : c).join('');
} else {
to = to[0];
const mapper = Object.assign({}, ...from.split('').map((f, i) => ({[f]: f})));
return str.split('').map(c => mapper.hasOwnProperty(c) ? mapper[c] : to).join('');
}
};
// not recommended, but you can if you want, then you can "hello".tr('el', 'ip')
String.prototype.tr = function(from, to) {
return tr(this, from, to);
};
console.log("hello".tr('el', 'ip')) //#=> "hippo"
console.log("hello".tr('aeiou', '*')) //#=> "h*ll*"
console.log("hello".tr('a-y', 'b-z')) //#=> "ifmmp"
console.log("hello".tr('^aeiou', '*')) //#=> "*e**o"
答案 1 :(得分:0)
我找到了答案,希望对想要实现此功能的人有所帮助:
function tr (str, from, to) {
var out = "", i, m, p ;
for (i = 0, m = str.length; i < m; i++) {
p = from.indexOf(str.charAt(i));
if (p >= 0) {
out = out + to.charAt(p);
}
else {
out += str.charAt(i);
}
}
return out;
}
答案 2 :(得分:-1)
您可以尝试
string.replace()链接在这里: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
var str = "hello world";
var subString = "hello";
var newSubstring = "girl";
var newString = str.replace(subString, newSubstring);
console.log(newString);