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.
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. If using ES6 then let
is preferred. 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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.