从字符串中删除空格、点和特殊字符并用 jQuery 中的连字符替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16161671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:34:43  来源:igfitidea点击:

Remove spaces , dots and special chars from a string and replace with hyphen in jQuery

javascriptjquery

提问by user1831498

I have a string where there may be special characters, which I have to replace with hyphen

我有一个字符串,其中可能有特殊字符,我必须用连字符替换

var str="123.This is,, :ravi"

The above string should be converted like this

上面的字符串应该像这样转换

var newstr="123-This-is-ravi";

I have been trying this

我一直在尝试这个

function remove(str){ str.replace(/\./g, "-"); }  //replaces only dots
function remove(str){ str.replace(/ /g, "-"); }   //replaces only spaces

Can any one help me doing this? I need to replace special chars with hyphen.

任何人都可以帮助我这样做吗?我需要用连字符替换特殊字符。

回答by pickypg

You should do the regular expression all at once:

应该一次完成正则表达式

"123.This is,, :ravi".replace(/[\. ,:-]+/g, "-")

Working example:

工作示例:

$('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>

That way it will not double up on hyphens.

这样它就不会在连字符上加倍。

One thing to note is that if the value ends with a period (dot), or even any whitespace, then it will end with a hyphen.

需要注意的一件事是,如果值以句点(点)或任何空格结尾,那么它将以连字符结尾。

回答by Iya F.

You could also try to globally replace any non-alphanumeric character and white space by using the function

您还可以尝试使用该函数全局替换任何非字母数字字符和空格

"123.This is,, :ravi".replace(/[\W_]/g, "-")

/[\W_]/g this globally eliminates any non alphanumeric characters and white spaces and can be replaced by anything you chose after the comma,

/[\W_]/g 这会在全局范围内消除任何非字母数字字符和空格,并且可以替换为您在逗号后选择的任何内容,