简体   繁体   English

替换javascript中的所有字符实例

[英]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 我想用\\r <br>替换<br> \\r

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

, but it is replacing only the first <br> ... Any idea why? ,但它只取代了第一个<br> ...任何想法为什么?

The code should work - with the /g flag, it should replace all <br> s. 该代码应工作-与/g标志,就应更换所有的<br>秒。 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. '\\n'可能比\\r更合适 - 它应该被全局识别为换行符,而\\r本身并不常见。 On Firefox, for example, \\r isn't rendered as a newline. 例如,在Firefox上, \\r不会呈现为换行符。

Use : 使用 :

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

/g is only for the first match. / g仅适用于第一场比赛。 /gi is for global replacement / gi是全球替代品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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