替换所有出现的字符串
可能重复:
Fastest method to replace all instances of a character in a string替换所有出现的字符串
你怎么能替换字符串中所有出现?
如果你想在一个字符串替换所有换行符(\ n)的..
这将只替换换行符
str.replace(/\\n/, '<br />');
中首次出现的我无法弄清楚如何做招?
使用全局标志。
str.replace(/\n/g, '<br />');
布里格斯回答用途literal regexp
。
带正则表达式对象的解决方案。
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
尝试在这里:JSFiddle Working Example
呃,*参数*是非标准的。在表达很好之后直接使用标志。除了使用RegExp构造函数(通常用于动态表达式)之外,你基本上和其他答案一样。 – 2011-05-19 21:46:48
@Matt说谁?在我的文章中有Mozilla的参考。你的参考在哪里? – 2011-05-19 21:47:56
你误解了源代码。 '//'是RegExp对象的文字形式。 MDC声明第三个(不是第一个)参数是非标准的。 – 2011-05-19 21:54:31
正如所解释的here,你可以使用:
function replaceall(str,replace,with_this)
{
var str_hasil ="";
var temp;
for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
{
if (str[i] == replace)
{
temp = with_this;
}
else
{
temp = str[i];
}
str_hasil += temp;
}
return str_hasil;
}
...然后就可以调用使用其中:
var str = "50.000.000";
alert(replaceall(str,'.',''));
功能将提醒“50000000”
删除bom字符请解释为什么downvotes .. – 2018-02-18 12:02:49
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace#Example.3a_Using_global_and_ignore_with_replace“非标准一个字符串,指定正则表达式的标志的组合。在String.replace方法中使用flags参数是非标准的。如果不使用此参数,使用RegExp对象与相应的标志。” – Beta033 2013-05-07 22:05:34
你对此有何意义?我的解决方案不使用非标准的标志参数。 – Brigham 2013-05-07 22:16:21
谢谢布里格姆。您的代码工作得很好... – csonuryilmaz 2013-05-08 15:00:04