开发者

Why does javascript replace only first instance when using replace? [duplicate]

This question already has answers here: 开发者_StackOverflow How do I replace all occurrences of a string in JavaScript? (79 answers) Closed 2 years ago.

I have this

 var date = $('#Date').val();

this get the value in the textbox what would look like this

12/31/2009

Now I do this on it

var id = 'c_' + date.replace("/", '');

and the result is

c_1231/2009

It misses the last '/' I don't understand why though.


You need to set the g flag to replace globally:

date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')

Otherwise only the first occurrence will be replaced.


Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the g‍lobal flag, which is not on by default, to replace all matches in one go.

If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:

var id= 'c_'+date.split('/').join('');


You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜