简体   繁体   中英

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?

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.

Use :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM