Javascript 替换javascript中的所有字符实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5619834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all instances of character in javascript
提问by Niraj Choubey
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
我想更换<br>
与\r
使用
str.replace(/<br>/g,'\r');
, but it is replacing only the first <br>
... Any idea why?
,但它只替换第一个<br>
......知道为什么吗?
回答by Kobi
The code should work - with the /g
flag, it should replace all <br>
s. It's possible the problem is elsewhere.
代码应该可以工作 - 使用/g
标志,它应该替换所有<br>
s。问题可能出在其他地方。
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.
'\n'
可能比\r
- 它应该被全球公认为换行符更合适,而\r
它本身并不常见。例如,在 Firefox 上,\r
它不会呈现为换行符。
回答by fen4o
Use :
用 :
str.replace(/<br>/gi,'\r');
/g is only for the first match. /gi is for global replacement
/g 仅用于第一场比赛。/gi 用于全局替换