admin管理员组

文章数量:1279207

I'm trying to write some code that will check if a previously defined variable has a space, and if it does, replace the space with a dash. This will be nested in another function.

function foo(){            
    // If stateName has a space replaces the space with a dash

    window.open('/state-solar-policy/' + stateName);
}

I'm trying to write some code that will check if a previously defined variable has a space, and if it does, replace the space with a dash. This will be nested in another function.

function foo(){            
    // If stateName has a space replaces the space with a dash

    window.open('http://website.html/state-solar-policy/' + stateName);
}
Share Improve this question edited Jun 27, 2012 at 21:23 Liam McInroy 4,3665 gold badges35 silver badges54 bronze badges asked Jun 27, 2012 at 21:15 user1486922user1486922 311 gold badge1 silver badge2 bronze badges 3
  • Here's the opposite, reverse the function args. – Michael Berkowski Commented Jun 27, 2012 at 21:18
  • 2 Why check? If there isn't a space to replace, nothing will happen, so you can forget the check. Just str = str.replace(' ','-'); – DanRedux Commented Jun 27, 2012 at 21:18
  • @DanRedux. " " is only one white space option. \s capture them all. – gdoron Commented Jun 27, 2012 at 21:19
Add a ment  | 

3 Answers 3

Reset to default 9

Use this regex:

stateName.replace(/\s/g,"-");

It will replace all white spaces chars with a dash (-)

Note that the regex will cause no troubles if the string doesn't have a space in it.
It replaces every white-space if finds with a dash, if it doesn't find, it does nothing.

var string = "blah blah blah"
var new_string = string.replace(" ", "-");
var string="john doe is great";
var dashedstring=string.split(" ").join("-");

本文标签: Javascript if string contains a space replace the space with a dashStack Overflow