replace all occurrences in a string [duplicate]
Possible Duplicate:
Fastest method to replace all instances of a character in a string
How can you replace all occurrences found in a string?
If you want to replace all the newline characters (\n) in a string..
This will only replace the first occurrence of newline
str.replace(/\\n/, '<br />');
I cant figure out how to do the trick?
Use the global flag.
str.replace(/\n/g, '<br />');
Brighams answer uses literal regexp
.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
As explained here, you can use:
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;
}
... which you can then call using:
var str = "50.000.000";
alert(replaceall(str,'.',''));
The function will alert "50000000"
精彩评论