Is it possible to replace all carriage returns in a string via .replace?

JavascriptReplace

Javascript Problem Overview


Is it possible to replace all carriage returns in a string with the .replace function? I've found quite a few complex functions to do it, but was wondering if it could be simplified with just a regex through .replace?

Thanks!

Javascript Solutions


Solution 1 - Javascript

Both \n (new line) and \r (carraige return) create a new line. To replace all instances of both at the same time:

s.replace(/[\n\r]/g, '');

Note that you might want to replace them with a single space rather than nothing.

Solution 2 - Javascript

Here how to do it

str = str.replace(/\r/gm,'newChar');

By default, Javascript replace() replaces the first occurance. The way around it is to set the first parameters as a regex.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkView Question on Stackoverflow
Solution 1 - JavascriptRobGView Answer on Stackoverflow
Solution 2 - JavascriptDavid LabergeView Answer on Stackoverflow