Replacing spaces with underscores in JavaScript?

Try .replace(/ /g,"_");

Edit: or .split(' ').join('_') if you have an aversion to REs

Edit: John Resig said:

If you’re searching and replacing
through a string with a static search
and a static replace it’s faster to
perform the action with
.split(“match”).join(“replace”) –
which seems counter-intuitive but it
manages to work that way in most
modern browsers. (There are changes
going in place to grossly improve the
performance of .replace(/match/g,
“replace”) in the next version of
Firefox – so the previous statement
won’t be the case for long.)

Leave a Comment