我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
var string = '#Please send_an_information_pack_to_the_following_address:';
我试过了:
string.replace('#','').replace('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
var string = '#Please send_an_information_pack_to_the_following_address:';
我试过了:
string.replace('#','').replace('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
当前回答
对于什么都不替换,tckmn的答案是最好的。
如果你需要替换对应匹配的特定字符串,下面是Voicu和Christophe回答的一个变体,避免重复被匹配的内容,这样你就不必记得在两个地方添加新的匹配:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
其他回答
如果你想替换多个字符,你可以调用String.prototype.replace(),替换参数是为每个匹配调用的函数。您所需要的只是一个表示将在该函数中使用的字符映射的对象。
例如,如果你想用x替换a,用y替换b,用z替换c,你可以这样做:
Const chars = { a:“x”, b:‘y’, “c”:“z” }; Let s = ' 234abc567bbbac '; S = S .replace(/[abc]/g, m => chars[m]); console.log(年代);
输出:234xyz567yyyyxz
捆绑很酷,为什么要抛弃它呢?
不管怎样,这里有一个替换的另一个选项:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
如果匹配==“#”,则替换将选择“”,如果不匹配则选择“”。
对于一个更通用的解决方案,你可以将替换字符串存储在一个对象中:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
可以用一个简单的正则表达式替换多个子字符串。 例如,我们想要将数字(123)456-7890转换为1234567890,我们可以这样做。
var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890
我们可以在[]之间传递要替换的子字符串,而要替换的字符串应该作为第二个参数传递给replace函数。
对于什么都不替换,tckmn的答案是最好的。
如果你需要替换对应匹配的特定字符串,下面是Voicu和Christophe回答的一个变体,避免重复被匹配的内容,这样你就不必记得在两个地方添加新的匹配:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
如果只是使用if else语句的简写呢?使它成为一行程序。
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );