chobo2 chobo2 - 1 year ago 98
jQuery Question

Why does javascript replace only first instance when using replace?

I have this

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

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


Now I do this on it

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

and the result is


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download