Question

I'm looking to improve a regex in JavaScript which looks for new lines or line breaks and replace them with carriage returns. - Yeah, Photoshop's text is old skool.

  • "hello\nworld"
  • "hello
    world"

Should all get replaced with

-hello/rworld

Yes, I'm aware the the second example above gets treated as an actual line break

So far I've had to use two regexs, whereas I really need one to look for both items (multiple times), but joining them together successfully it eludes me.

// replaces \n with \r carriage return
var rexp = new RegExp(/\\n/gi)
content = content.replace(rexp , "\r")

// replaces <br> with \r carriage return
rexp = new RegExp(/<br>/gi)
content = content.replace(rexp , "\r")

Thank you.

Was it helpful?

Solution

You can use "special | or" operator:

content = content.replace(/\n|<br\s*\/?>/gi, "\r");

It will successfully work for:

"hello\nworld"
"hello<br>world"
"hello<br />world"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top