12

I have a string

 var str=  'asdf<br>dfsdfs<br>dsfsdf<br>fsfs<br>dfsdf<br>fsdf';

I want to replace <br> with \r by using

 str.replace(/<br>/g,'\r');

, but it is replacing only the first <br>... Any idea why?

3
  • replace(/<br>/g,'\r') replaces all <br> here ... Or did you only want to replace the first <br>? Commented Apr 11, 2011 at 10:17
  • 1
    Something else must be going on. The code snippet you pasted does what you want. Here's the output from node.js:` 'asdf<br>dfsdfs<br>dsfsdf<br>fsfs<br>dfsdf<br>fsdf'.replace(/<br>/g,'\r') = 'asdf\rdfsdfs\rdsfsdf\rfsfs\rdfsdf\rfsdf'` Commented Apr 11, 2011 at 10:18
  • This should work, have you made sure this is the original code? Commented Apr 11, 2011 at 10:19

2 Answers 2

33

The code should work - with the /g flag, it should replace all <br>s. It's possible the problem is elsewhere.

Try this:

str = str.replace(/<br>/g, '\n');

'\n' is probably more appropriate than \r - it should be globally recognized as a newline, while \r isn't common on its own. On Firefox, for example, \r isn't rendered as a newline.

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

Comments

-9

Use :

str.replace(/<br>/gi,'\r');

/g is only for the first match. /gi is for global replacement

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.