[javascript] replace all occurrences in a string

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?

This question is related to javascript regex

The answer is


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"


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