I want to find exact occurrences of all \n
and :
and replace the string in between with a specific string.
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.
\n([^\n:]+):
Replace with
<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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.