我试图用相应的值替换不同的设置字符.例如,每个<替换为#U34,每个$替换为#89.
我有一个字符串数组,随机抛出这些字符.例如:
var arr = [
'uisdhfu<',
'u$$fd<'
]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我发现我能做到:
var replace = /</ig;
var newString = textWithCharacters.replace(replace, '#U34');
Run Code Online (Sandbox Code Playgroud)
但这似乎只能一次为一个角色完成.如果我想做多个,我似乎每次都需要创建一个新的字符串.有没有办法一次性完成这项工作?也许有循环和if语句?但我似乎无法弄清楚我将如何定义循环的条件.
该.replace()方法接受第二个参数的函数,该函数传递匹配的字符串(例如'<'),并返回替换文本(例如'#U34').
所以,你可以这样做:
var replacementMap = {
'<': '#U34',
'$': ')#89'
}
// Create a RegExp to match any of the characters that are used as keys in the map.
// For this example, this RegExp is the same as /[<$]/gi
// Note: this method of creating a RegExp may not work with certain characters such
// as -, ], or \
var replaceRegex = new RegExp('[' + Object.keys(replacementMap).join('') + ']', 'ig');
function getReplacementString(input) {
return replacementMap[input];
}
var newString = textWithCharacters.replace(replaceRegex, getReplacementString);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1839 次 |
| 最近记录: |