Arshad Shaikh
Arshad Shaikh

Reputation: 21

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.

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)

Upvotes: 1

Views: 57

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

You can exclude matching both using an negated character 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

Upvotes: 1

Related Questions