1

I had

return value.replace("\n","<br>")
            .replace("\r","<br>")
            .replace("<br><br>","<br>");

which only replaced the first occurence of \n with

I found that, to replace all occurences, I should replace String with /String/g

So I did:

return value.replace("/\n/g","<br>")
            .replace("/\r/g","<br>")
            .replace("/<br><br>/g","<br>");

But it seems as if I am missing something, since nothing is replaced.

3
  • Why wouldn't you use (?:\r?\n|\r) ? Commented Mar 24, 2014 at 17:54
  • I don't know why you want to do this, but look into the CSS white-space property, especially the pre-wrap and pre-line values. Commented Mar 24, 2014 at 17:55
  • 1
    You have to pass a regular expression, not a string. Commented Mar 24, 2014 at 17:55

3 Answers 3

3

Remove the double quotes around the regex:

return value.replace(/\n/g,"<br>")
        .replace(/\r/g,"<br>")
        .replace(/<br><br>/g,"<br>");
Sign up to request clarification or add additional context in comments.

Comments

1

You should remove quotes. And by the way, you can use this single and simple regex.

Use this:

return value.replace(/\n|\r|<br><br>/g,"<br>");

Comments

1

When you use a literal string, don't use the quotes. This means your code becomes:

return value.replace(/\n/g,"<br>")
            .replace(/\r/g,"<br>")
            .replace(/<br><br>/g,"<br>");

But with regex, you can actually make it shorter by using character classes. For instance, if value does not have any <br> initially, you can use this:

return value.replace(/[\r\n]+/g, "<br>");

But if your initial code has <br> from the start, then you can use something more like this:

return value.replace(/(?:[\r\n]|<br>)+/g, "<br>");

Or perhaps maybe use definite quantifiers if you want to keep consecutive newlines:

return value.replace(/[\r\n]{2}/g, "<br>");

or

return value.replace(/(?:[\r\n]|<br>){2}/g, "<br>");

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.