458

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);
}
Jason S
  • 184,598
  • 164
  • 608
  • 970
Ali
  • 261,656
  • 265
  • 575
  • 769

11 Answers11

885

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
  • 115,249
  • 25
  • 154
  • 140
95

try this:

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

that'll do a global find/replace

javascript replace

Adam
  • 7,800
  • 2
  • 25
  • 24
71

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,"_");
GoTo
  • 5,966
  • 2
  • 28
  • 31
Rich
  • 36,270
  • 31
  • 115
  • 154
54

You can try this

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

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

Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
20

Replace spaces with underscore

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

Output: How_are_you

Arshid KV
  • 9,631
  • 3
  • 35
  • 36
19

I created JS performance test for it http://jsperf.com/split-and-join-vs-replace2

Inez
  • 2,115
  • 3
  • 20
  • 25
  • 1
    it seems nowadays replace is the better overall choice – Houman Sep 25 '12 at 10:01
  • Kave - what? Although not all browsers are equal, split/join on average is much better. In fact, in a lot of modern browsers, it's a tone better! Thanks Inez for setting this up! – David Hobs Oct 21 '12 at 00:13
  • 4
    A little over a year later now and running that above test in Chrome 32.0.1700.107 .. str.replace() yields far better results (64% faster) – jenovachild Feb 12 '14 at 04:50
8

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,"_"));
  2. Using replaceAll method:

    The replaceAll method will remove all spaces with an underscore. (must use the global flag with it when using regex)

        function updateKey()
        {
            var key=$("#title").val();
            key=key.replaceAll(/ /g,"_");
            // key=key.replaceAll(" ","_"); also valid
            $("#url_key").val(key);
        }
        // Show case
        let title = "Your document title";
        console.log(title.replaceAll(/ /g,"_"));
  3. Use a combination of split and join method:

    Split your string at spaces and join it by using _ as a separator in the join method.

        function updateKey()
        {
            var key=$("#title").val();
            key=key.split(" ").join("_");
            $("#url_key").val(key);
        }
        // Show case
        let title = "Your document title";
        console.log(title.split(" ").join("_"));
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Satish Chandra Gupta
  • 2,970
  • 1
  • 22
  • 22
4

Just using replace:

var text = 'Hello World';
    
new_text = text.replaceAll(' ', '_');
    
console.log(new_text);
Vibhu kumar
  • 386
  • 3
  • 8
3

I know this is old but I didn't see anyone mention extending the String prototype.

String.prototype.replaceAll = function(search, replace){
    if(!search || !replace){return this;} //if search entry or replace entry empty return the string
    return this.replace(new RegExp('[' + search + ']', 'g'), replace); //global RegEx search for all instances ("g") of your search entry and replace them all.
};
BlueEyesWhiteDragon
  • 427
  • 1
  • 6
  • 20
  • 4
    You didn't see anyone do it as it's a terrible idea. [Check out this other SO question for more.](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) –  May 15 '18 at 19:05
1

const updateKey = key => console.log(key.split(' ').join('_'));
updateKey('Hello World');
lethalSid
  • 51
  • 3
0
$(function() {
    $('#title').keyup(function() {
        var value = $(this).val().toLowerCase();
        $('#url_key').val(value.split(' ').join('_'));
    }).keyup();
});

-- or you can use:

$(function() {
    $('#title').keyup(function() {
        var value = $(this).val().toLowerCase();
        $('#url_key').val(value.replace(/ /g,"_"));
    }).keyup();
});
Jaber
  • 9
  • 7