正则表达式 - 匹配一个没有空格的字符串

时间:2017-02-10 09:15:26

标签: javascript regex spaces

构建一个将拒绝包含空格的输入字符串的正则表达式。

我有一个下面的表达,但它不起作用;

^[a-zA-Z0-9!@#*()+{}[\\];:,|\/\\\\_\S-]+$

有效案例

String123/test //string without space

无效案例

String123/ test // contains space in between string 

String 123/test // contains space in between string 

 String123/test  // contains leading\trailing space

即;我必须使用不包含任何空格的白名单字符串。

2 个答案:

答案 0 :(得分:5)

您可以使用\S

\S匹配任何非空格字符

<强>正则表达式

/^\S+$/g

示例

&#13;
&#13;
function CheckValid(str){
   re = /^\S+$/g
   return re.test(str)
 }


console.log(CheckValid("sasa sasa"))
console.log(CheckValid("sasa/sasa"))                      
console.log(CheckValid("sas&2a/sasa"))                      
                       
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为你将在regex上使用.test方法,/\s/g这个应该完成这项工作,如果字符串中有任何空格,它将返回true。 例如:/\s/g.test("String123/test")这将返回false,这意味着该字符串有效 /\s/g.test("String123 /test)这将返回true,表示该字符串无效