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);
}

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

9

try this:

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

that'll do a global find/replace

javascript replace

1

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,"_");

You can try this

 var str = 'hello     world  !!';
 str = str.replace(/\s+/g, '-');

It will even replace multiple spaces with single '-'.

1

I created JS performance test for it

3

Replace spaces with underscore

var str = 'How are you';
var replaced = str.split(' ').join('_');

Output: How_are_you

Replace all occurrences

This is happening because replace() method is designed this way to replace only the first occurance when you use string to find the match. Check the replace method.

To replace all matches you can use the following 3 methods:

  1. use regex with the global flag in replace() method:

    When you use the replace method with regex with /g flag it replaces all the matching occurrences in a string.

        function updateKey()
        {
            var key=$("#title").val();
            key=key.replace(/ /g,"_");
            $("#url_key").val(key);
        }
        // Show case
        let title = "Your document title";
        console.log(title.replace(/ /g,"_"));
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.