简体   繁体   English

从JS中的字符串中删除所有特殊字符

[英]Remove all special characters from string in JS

I want to remove all special characters from string and add only one "-"(hyphen) in the place.我想从字符串中删除所有特殊字符,并在该位置仅添加一个“-”(连字符)。

Consider below example考虑下面的例子

var string = 'Lorem%^$&*&^Ipsum#^is@!^&simply!dummy text.'

So, from the above string, if there is a continuous number of special characters then I want to remove all of them and add only one "-" or if there is a single or double special character then also that should be replaced by "-"因此,从上面的字符串中,如果有连续数量的特殊字符,那么我想删除所有特殊字符并只添加一个“-”,或者如果有一个或两个特殊字符,那么也应该用“-”替换”

Result should be like this结果应该是这样的

Lorem-Ipsum-is-simply-dummy text-

I have tried below, but no luck我在下面尝试过,但没有运气

var newString = sourceString.replace(/[\. ,:-]+/g, "-");

You could use .replace to replace all non-alphabetical character substrings with - :您可以使用.replace将所有非字母字符子串替换为-

 const input = 'Lorem%^$&*&^Ipsum#^is@!^&simply!dummy text.'; const output = input.replace(/[^\\w\\s]+/gi, '-'); console.log(output);

If you want to permit numbers too:如果您也想允许数字:

 const input = 'Lorem123%^$&*&^654Ipsum#^is@!^&simply!dummy text.'; const output = input.replace(/[^\\w\\s\\d]+/gi, '-'); console.log(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM