Niraj Choubey
Niraj Choubey

Reputation: 4040

Replace all instances of character in javascript

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?

Upvotes: 12

Views: 34515

Answers (2)

fen4o
fen4o

Reputation: 1

Use :

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

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

Upvotes: -9

Kobi
Kobi

Reputation: 138017

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.

Upvotes: 33

Related Questions