[英]Replacing multiple occurences of abbreviations in a string
I need to replace multiple abbreviations in a string. 我需要替换字符串中的多个缩写。
Result should be: 结果应为:
One DUMMY_0 two DUMMY_0 three DUMMY_0 four profession
What am I doing wrong? 我究竟做错了什么?
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);
Remove '\\b'
from regex. 从正则表达式中删除'\\b'
。
Also you will have to escape special characters. 另外,您将必须转义特殊字符。
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; }) }
.
添加了通用解析器来处理以外的特殊字符.
. 。 const
with var
inside loop. 用var
内部循环替换const
。 If using ES6 then let
is preferred. 如果使用ES6,则首选let
。 First, you have to remove \\b
in your regex (why did you write that there?), second: you have to escape the dots in your regexes, because dot means "any character" in a regular expression. 首先,您必须删除正则表达式中的\\b
(为什么在那写呢?),其次:您必须对正则表达式中的点进行转义,因为点在正则表达式中表示“任何字符”。
The modified code: 修改后的代码:
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);
Edit: Added escaping in the loop 编辑:在循环中添加了转义
An alternative way of solving this issue, with less code and without regex. 解决此问题的另一种方法,使用较少的代码,而无需使用正则表达式。
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.