[英]Regex wont understand white space
Have code: 有代码:
var regexp = new RegExp("[^a-zA-Z\-\s]", "g");
val = val.replace(regexp,'');
It need too leave letters ( a-zA-Z ), - ( \\- ) and white spaces ( \\s ) and remove all other symbols. 它也需要保留字母( a-zA-Z ),-( \\- )和空格( \\ s ),并删除所有其他符号。
But now it remove white spaces too. 但是现在它也删除了空格。
What am I doing wrong? 我究竟做错了什么?
You need to double the backslashes: 您需要将反斜杠加倍:
var regexp = new RegExp("[^a-zA-Z\\-\\s]", "g");
or, better, use a regex literal (and simplify it): 或者,最好使用正则表达式文字(并简化它):
var regexp = /[^a-z\s-]/gi;
Your slashes need to be escaped in a string literal. 您的斜杠必须以字符串文字进行转义。
A simple solution is to use a regex literal : 一个简单的解决方案是使用正则表达式文字 :
var regexp = /[^a-zA-Z\-\s]/g
Here is a JavaScript Regex Generator tool i came across if anyone is interested. 如果有人感兴趣,这是我遇到的JavaScript Regex Generator工具 。
Was quite useful for regex amateurs like me. 对于像我这样的正则表达式业余爱好者来说非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.