正则表达式,用于用连字符替换字符串中的所有特殊字符和空格 [英] Regex for replacing all special characters and spaces in a string with hyphens

查看:148
本文介绍了正则表达式,用于用连字符替换字符串中的所有特殊字符和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

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

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

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

但是它正在输出:

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.

推荐答案

我建议:

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

JS小提琴演示.

这篇关于正则表达式,用于用连字符替换字符串中的所有特殊字符和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆