开发者

replace all occurrences in a string [duplicate]

This question already has answers here: 开发者_如何转开发 Closed 10 years ago.

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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜