jQuery 用连字符替换字符串中所有特殊字符和空格的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18936483/
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 22:48:26  来源:igfitidea点击:

Regex for replacing all special characters and spaces in a string with hyphens

jquery

提问by user2643287

I have a string in which I need to replace all the special characters "~!@#$%^&*()_+=`{}[]|:;'<>,./?" and spaces with hyphens. Multiple special characters in a row should result in a single hyphen.

我有一个字符串,我需要在其中替换所有特殊字符 "~!@#$%^&*()_+=`{}[]|:;'<>,./?" 和带连字符的空格。一行中的多个特殊字符应生成一个连字符。

var mystring="Need !@#$%^\" to /replace  this*(){}{}|\><? with_new string ";
// desired output: "Need-to-replace-this-with-new-string"

At present, I'm using this series of replace()calls:

目前,我正在使用这一系列的replace()调用:

return mystring.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-').replace(/\//g, "-");

But it's outputting this:

但它输出的是:

Need----------to/replace-this--------with-new-string;

where it's adding a hyphen for every special character in the string except for the forward slash.

它为字符串中的每个特殊字符添加一个连字符,除了正斜杠。

回答by David says reinstate Monica

I'd suggest:

我建议:

var inputString = "~!@#$%^&*()_+=`{}[]|\:;'<>,./?Some actual text to keep, maybe...",
    outputString = inputString.replace(/([~!@#$%^&*()_+=`{}\[\]\|\:;'<>,.\/? ])+/g, '-').replace(/^(-)+|(-)+$/g,'');
console.log(outputString);

JS Fiddle demo.

JS小提琴演示

回答by Paul Roub

Going by your comment and example:

根据您的评论和示例:

return mystring.trim().replace(/["~!@#$%^&*\(\)_+=`{}\[\]\|\:;'<>,.\/?"\- \t\r\n]+/g, '-');

or to replace allnon-alphanumeric characters:

或替换所有非字母数字字符:

return mystring.trim().replace(/[^a-z0-9]+/gi, '-');

You might also add:

您还可以添加:

.replace(/^-+/, '').replace(/-+$/, '');

to kill off any leading or trailing dashes (at which point you no longer need to call trim()).

消除任何前导或尾随的破折号(此时您不再需要调用trim())。

Example:

例子:

function cleanUp(st) {
  return st.
     replace(/[^a-z0-9]+/gi, '-').
     replace(/^-+/, '').
     replace(/-+$/, '');
}

var mystring="Need !@#$%^\" to /replace  this*(){}{}|\><? with_new string ";

console.log( cleanUp(mystring) );