2 回答
TA贡献1789条经验 获得超10个赞
制作一个对象映射字符到它们的替换,然后从对象的键构造一个正则表达式:
const replacements = {
0: 'A',
1: 'B',
2: 'Y',
3: 'Z',
};
const pattern = new RegExp(Object.keys(replacements).join('|'), 'g');
console.log('string01230123'.replace(pattern, char => replacements[char]));
另一种方法是更简洁地构造对象,如果您有很多字符要替换:
const replacements = Object.fromEntries(
`
0 A
1 B
2 Y
3 Z
`
.split('\n')
.filter(Boolean)
.map(line => [line[0], line[2]])
);
const pattern = new RegExp(Object.keys(replacements).join('|'), 'g');
console.log('string01230123'.replace(pattern, char => replacements[char]));
TA贡献1862条经验 获得超7个赞
您可以重新创建相同的方法。将不得不创建一个将两者结合起来的查找对象,然后使用正则表达式或某种循环来进行替换。
const strtr = (str, matches, replacements) => {
const matchesArr = matches.split('');
const lookup = matchesArr.reduce((o, c, i) => ({ ...o,
[c]: replacements[i]
}), {});
return str.replace(new RegExp(matchesArr.join('|'), 'g'), x => lookup[x]);
}
console.log(strtr('string01230123', '0123', 'ABYZ'));
const strtr2 = (str, matches, replacements) => {
const matchesArr = matches.split('');
const lookup = matchesArr.reduce((o, c, i) => ({ ...o,
[c]: replacements[i]
}), {});
return str.split('').map(x => lookup[x] || x).join('')
}
console.log(strtr2('string01230123', '0123', 'ABYZ'));
添加回答
举报