[英]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.