Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing spaces with underscores in JavaScript?

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); } 
like image 782
Ali Avatar asked Jan 13 '09 22:01

Ali


People also ask

How do you replace a space in JavaScript?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.


2 Answers

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

like image 89
Crescent Fresh Avatar answered Oct 05 '22 13:10

Crescent Fresh


try this:

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

that'll do a global find/replace

javascript replace

like image 32
Adam Avatar answered Oct 05 '22 12:10

Adam