Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if string contains a space replace the space with a dash

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);
}
like image 631
user1486922 Avatar asked Mar 28 '26 03:03

user1486922


1 Answers

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.

like image 119
gdoron is supporting Monica Avatar answered Mar 29 '26 17:03

gdoron is supporting Monica