简体   繁体   中英

Does JavaScript have a method like Ruby's 'tr' method?

JavaScript是否具有类似Ruby的tr方法的方法

string.tr('0123456789','9876543210')

Here's an implementation I just threw together now

As far as I know, it follows the ruby implementation

Several things I don't know about ruby implementation are

  1. What if the from or to string contains a trailing or leading dash?
  2. What if you put a range like 9-0, ie high to low?
  3. If from starts with ^ and to is more than one character, should that be an error? or just use the first character ignoring the rest?

This code simply uses dash as a dash if it's the first or last in the string, and 9-0 will become 9876543210

Anyway, hopefully this is enough

 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(hl); l += sgn; h -= sgn; return Array.from({length:Math.abs(hl)+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" 

I have find the answer , hope help someone who want implement this function:

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;
}

can you try the

string.replace()
Here is the link: 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM