簡體   English   中英

在所有出現的字符串字符 javascript 中替換字符串

[英]Replace string within all occurrences of a string character javascript

我想找到所有\n:的確切出現,並將其間的字符串替換為特定字符串。

例如,給定這個輸入:

 Testing \n string of character \n June,23 2020: the task was completed. \n April,4 2020: All looks \n good

預期的結果是這樣的:

 Testing \n string of character <br><b> June,23 2020</b><br> the task was completed. <br><b> April,4 2020</b></br> All looks \n good

 const text=`Testing \n string of character \n June,23 2020: the task was completed. \n April,4 2020: All looks \n good`; const newlineColonRegex = /(\n|:)/g const replaceWith = '<br><b>' const newString = text.replace(newlineColonRegex, replaceWith) console.log(newString)

您可以使用否定字符 class 排除兩者的匹配。

\n([^\n:]+):

用。。。來代替

<br><br>$1<br><br>

正則表達式演示

 const regex = /\n([^\n:]+:)/g; const text = `Testing \n string of character \n June,23 2020: the task was completed. \n April,4 2020: All looks \n good`; const newlineColonRegex = /\n([^\n:]+):/g; const replaceWith = '<br><br>$1<br><br>' const newString = text.replace(newlineColonRegex, replaceWith) console.log(newString)


如果您還想從字符串的開頭匹配它,您可以使用錨點而不是換行符^([^\n:]+:)並使用/gm標志

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM