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
3 Answers
Reset to default 9Use 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
版权声明:本文标题:Javascript if string contains a space replace the space with a dash - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741268820a2368925.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论