Categories
JavaScript Answers

How to fix the string replace method not replacing text containing literal \r\n strings in JavaScript?

Spread the love

Sometimes, we want to fix the string replace method not replacing text containing literal \r\n strings in JavaScript.

In this article, we’ll look at how to fix the string replace method not replacing text containing literal \r\n strings in JavaScript.

How to fix the string replace method not replacing text containing literal \r\n strings in JavaScript?

To fix the string replace method not replacing text containing literal \r\n strings in JavaScript, we can call replace with a regex to match all instances of \r\n and replace them with the characters we want.

For instance, we write:

const value = 'abc\r\ndef'
const newVal = value.replace(/(?:\\[rn]|[\r\n])/g, "");
console.log(newVal)

to call value.replace to replace all instances of \r\n with empty strings.

We use the /(?:\\[rn]|[\r\n])/g regex to find all instances of \r\n in value.

As a result, newVal is "abcdef".

Conclusion

To fix the string replace method not replacing text containing literal \r\n strings in JavaScript, we can call replace with a regex to match all instances of \r\n and replace them with the characters we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *