繁体   English   中英

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

[英]Replacing multiple occurences of abbreviations in a string

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

结果应为:

One DUMMY_0 two DUMMY_0 three DUMMY_0 four profession

我究竟做错了什么?

 const abbr = ['vs.', 'po']; 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); 

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

另外,您将必须转义特殊字符。

 const abbr = ['vs.', 'po']; 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

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

首先,您必须删除正则表达式中的\\b (为什么在那写呢?),其次:您必须对正则表达式中的点进行转义,因为点在正则表达式中表示“任何字符”。

修改后的代码:

 const abbr = ['vs.', 'po']; 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); 

编辑:在循环中添加了转义

解决此问题的另一种方法,使用较少的代码,而无需使用正则表达式。

 const abbr = ['vs.', 'po']; let str = 'One vs. two vs. three vs. four profession'; abbr.forEach((ab, index) => { str = str.split(ab).join('DUMMY_' + index); }); console.log(str); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM