我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。

var string = '#Please send_an_information_pack_to_the_following_address:';

我试过了:

string.replace('#','').replace('_', ' ');

我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?


当前回答

捆绑很酷,为什么要抛弃它呢?

不管怎样,这里有一个替换的另一个选项:

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函数。

我不知道这有多大帮助,但我想从我的字符串中删除<b>和</b>

所以我用了

mystring.replace('<b>',' ').replace('</b>','');

所以基本上,如果你想要减少有限数量的字符,不浪费时间,这将是有用的。

对于什么都不替换,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

或者选择对我来说很好 示例let sample_string = <strong>一些带有html标签的单词</strong> |。需要删除强标签和“|”文本。 代码如下:= sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")