replace all occurrences in a string

JavascriptRegex

Javascript Problem Overview


> 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?

Javascript Solutions


Solution 1 - Javascript

Use the global flag.

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclarkkView Question on Stackoverflow
Solution 1 - JavascriptBrighamView Answer on Stackoverflow
Solution 2 - JavascriptKerem BaydoğanView Answer on Stackoverflow
Solution 3 - JavascriptDika ArtaView Answer on Stackoverflow