簡體   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