繁体   English   中英

正则表达式删除字母数字,但在Javascript中保留括号和空格

[英]Regex remove alphanumeric but keep parenthesis and spaces in Javascript

我有一个看起来像这样的字符串:

var string = 'Size? [Small] Color? [Blue]'

我想删除所有non alphanumeric但保留spaces[]

结束字符串为

'Size [Small] Color [Blue]'

我这样尝试\\ W:

string = string.replace(/\\W/g, '')

但这摆脱了空格和[]

我不确定如何在正则表达式中排除和包含项目?

我会将您想要的字符列入白名单而不是黑名单:

string.replace(/[^\w[\] ]/g, '');

\\W匹配所有非单词字符。

要匹配除空格以外的所有非字母数字, []您应使用否定的字符类:

/[^a-zA-Z0-9 \[\]]/

正则演示

码:

 let string = 'Size? [Small] Color? [Blue]'; string = string.replace(/[^a-zA-Z0-9 \\[\\]]+/g, '') console.log( string ); //=> Size [Small] Color [Blue] 

暂无
暂无

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

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