我有一个字符串,其中可能有特殊字符,我必须用连字符替换它
var str="123.This is,, :ravi"
上面的字符串应该这样转换
var newstr="123-This-is-ravi";
我一直在尝试这个
function remove(str){ str.replace(/\./g, "-"); } //replaces only dots
function remove(str){ str.replace(/ /g, "-"); } //replaces only spaces
谁能帮我做这件事?我需要用连字符替换特殊字符。
最佳答案
你 should do the regular expression all at once :
"123.This is,, :ravi".replace(/[\. ,:-]+/g, "-")
工作示例:
$('p').html("123.This is,, :ravi".replace(/[\. ,:-]+/g, "-"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
这样它就不会在连字符上加倍。
需要注意的一点是,如果值以句点(点)或什至任何空格结尾,那么它将以连字符结尾。
关于javascript - 从字符串中删除空格、点和特殊字符,并在 jQuery 中用连字符替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16161671/