views:

7054

answers:

5

I'm trying to use this code to replace spaces with _, it works for the first space in the string but all the other instances of spaces remain unchanged. Anybody know why?

function updateKey()
{
    var key=$("#title").val();
    key=key.replace(" ","_");
    $("#url_key").val(key);
}
+10  A: 

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.)

Crescent Fresh
bah! u beat me by 58secs! i shouldn't have added the key=key.!!! lol
Adam
Had it in my clipboard anyway. What are the odds.
Crescent Fresh
Is there any way to do this without the regexp?
Click Upvote
.split(' ').join('_')
Crescent Fresh
regex: now you have TWO problems! ha ha. Actually, this is one area where plain old split/join might be a better choice, especially if the codebase will be shared amongst less-than-expert peers who may need to poke through things without you to guide them.
matt lohkamp
Reason why the people who answered did not use /\s/g ?
epascarello
\s matches all whitespace
I.devries
Wouldn't the split/join solution generate a lot of overhead, allocating and deallocating many strings where the solution could just run in-place?
Thomas
@Thomas: see my latest edit to this answer
Crescent Fresh
+5  A: 

try this:

key=key.replace(/ /g,"_");

that'll do a global find/replace

javascript replace

Adam
A: 

How do you replace multiple spaces by single space in Javascript ?

+1  A: 

To answer Prasanna's question below:

How do you replace multiple spaces by single space in Javascript ?

You would use the same function (replace) with a different regular expression. The expression for whitespace is "\s" and the expression for "1 or more times" is the plus sign, so you'd just replace Adam's answer with the following:

key=key.replace(/\s+/g," ");
Rich
A: 

Good john Resig

Nares K