1

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)

1
  • I edited your question to use code blocks instead of block quotes. In the process I also removed extra spaces in the <b> and <br> tags that I believe (based on your code snippet) were accidentally inserted by SO's blockquote code, but wanted to note it here in case those were intentional. Commented Jun 2, 2021 at 15:56

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.