简体   繁体   English

在所有出现的字符串字符 javascript 中替换字符串

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

I want to find exact occurrences of all \n and : and replace the string in between with a specific string.我想找到所有\n:的确切出现,并将其间的字符串替换为特定字符串。

For example, given this input:例如,给定这个输入:

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

The expected result is this:预期的结果是这样的:

 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)

You can exclude matching both using an negated character class.您可以使用否定字符 class 排除两者的匹配。

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

Replace with用。。。来代替

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

Regex demo正则表达式演示

 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)


If you also want to match it from the start of the string, you could use an anchor instead of a newline ^([^\n:]+:) and use the /gm flags如果您还想从字符串的开头匹配它,您可以使用锚点而不是换行符^([^\n:]+:)并使用/gm标志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM