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

前端之家收集整理的这篇文章主要介绍了jquery – 使用连字符替换字符串中所有特殊字符和空格的正则表达式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个字符串,我需要替换所有特殊字符“〜!@#$%^& *()_ =`{} [] |:;’<>,./?”和连字符的空格.一行中的多个特殊字符应该生成一个连字符.
var mystring="Need !@#$%^\" to /replace  this*(){}{}|\><? with_new string ";
// desired output: "Need-to-replace-this-with-new-string"

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

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

但它正在输出

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

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

解决方法

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

JS Fiddle demo.

原文链接:https://www.f2er.com/jquery/176194.html

猜你在找的jQuery相关文章