简体   繁体   English

正则表达式转义空格和特殊字符

[英]regex escape spaces and special characters

I'm getting a console error: 我收到一个控制台错误:

Cannot call method 'replace' 无法调用方法'替换'

What I wanted to achieve is to escape all special characters and spaces. 我想要实现的是逃避所有特殊字符和空格。

text.replace(/[.*+?^${}()|[\]\/\\]/g, '\\$0');

So, when I have a string 所以,当我有一个字符串

"dfgsdfgsdfg) )( &( ^)( )& dfgdg123123sdfg" “dfgsdfgsdfg) )( &( ^)( )&dfgdg123123sdfg”

it should be read only as "dfgsdfgsdfgdfgdg123123sdfg" 它应该只读为"dfgsdfgsdfgdfgdg123123sdfg"

Note: I want to escape/ignore all non-alphanumeric characters and that includes spaces. 注意:我想要转义/忽略所有非字母数字字符,包括空格。 It should only be [a-zA-Z0-9] 它应该只是[a-zA-Z0-9]

PS newbie in regex. PS新手在正则表达式。

Probably the best approach is to match for "not alphanumeric", like so: 可能最好的方法是匹配“不是字母数字”,如下所示:

var text="dfgsdfgsdfg))(&(^)()& dfgdg123123sdfg";
alert(text.replace(/[^a-zA-Z0-9]/g, ''));

JS Fiddle Demo JS小提琴演示

Try this instead. 试试这个。

text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");

Or just match any non-word character which would be the best approach for this. 或者只是匹配任何非单词字符,这将是最好的方法。

text.replace(/\W/g, '');

Try this: 尝试这个:

$(document).ready(function(){
 var str = "dfgsdfgsdfg))(&(^)()& dfgdg123123sdfg";
alert(str.replace(/[&/\#,+()$~%.'":*?<>{}^ ]/g, ""));
});

DEMO DEMO

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

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