替换字符串中多个缩写的出现

时间:2016-10-07 11:55:26

标签: javascript regex string replace

我需要替换字符串中的多个缩写。

结果应该是:

One DUMMY_0 two DUMMY_0 three DUMMY_0 four profession

我做错了什么?

const abbr = ['vs.', 'p.o.'];
let str = 'One vs. two vs. three vs. four profession';

abbr.forEach((ab, index) => {
  const regex = new RegExp('\b' + ab + '\b', 'g');
  str = str.replace(regex, 'DUMMY_' + index);
});
console.log(str);

3 个答案:

答案 0 :(得分:2)

从正则表达式中删除'\b'

此外,你必须逃避特殊字符。



const abbr = ['vs.', 'p.o.'];
let str = 'One vs. two vs. three vs. four profession';

abbr.forEach(function(ab, index) {
  var regex = new RegExp(getParsedString(ab), 'g');
  str = str.replace(regex, ('DUMMY_' + index));
});
console.log(str);

function getParsedString(str) {
  var specialChars = /(?:\.|\!|@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\+|\-|\=)/g;
  return str.replace(specialChars, function(v) {
    return "\\" + v;
  })
}




编辑1

  • 添加了一个通用解析器来处理.以外的特殊字符。
  • const内部循环替换var。如果使用ES6,则首选let
  • 删除箭头功能不需要上下文绑定

答案 1 :(得分:2)

首先,你必须删除你的正则表达式中的\b(为什么你在那里写?),第二:你必须逃避正则表达式中的点,因为点意味着"任何字符&#34 ;用正则表达式。

修改后的代码:



const abbr = ['vs.', 'p.o.'];
    let str = 'One vs. two vs. three vs. four profession';
    
    abbr.forEach((ab, index) => {
      const regex = new RegExp(ab.replace(/\./, "\\."), 'g');
      str = str.replace(regex, 'DUMMY_' + index);
    });
    console.log(str);




修改:在循环中添加了转义

答案 2 :(得分:2)

解决此问题的另一种方法,代码更少,没有正则表达式。



const abbr = ['vs.', 'p.o.'];
let str = 'One vs. two vs. three vs. four profession';

abbr.forEach((ab, index) => {
  str = str.split(ab).join('DUMMY_' + index);
});
console.log(str);




相关问题