views:

242

answers:

2

Hi

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.

+12  A: 

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.

Gumbo
Why difference then C# replace. Thought it would replace all occurrences by default. But why did it take 2 slashes away if it is only first occurrence?
chobo2
@chobo2 it didn't take away two slashes. There were only two to begin with, and it removed the first one.
Doug Neiner
@chobo2: Well, JavaScript is not C#. And `12/31/2009` does only contain two slashes.
Gumbo
Lol I am seeing things.
chobo2
+1  A: 

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('');
bobince