[英]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; }) }
.
。 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.