Regex - match a string without having spaces

早过忘川 提交于 2019-12-02 03:06:47

问题


Building an regular expression that will reject an input string which contain spaces.

I have a following expression, but its not working as well;

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

Valid case

String123/test //string without space

Invalid case

String123/ test // contains space in between string 

String 123/test // contains space in between string 

 String123/test  // contains leading\trailing space

i.e; I have to white list strings which does not contain any spaces.


回答1:


You may use \S

\S matches any non white space character

Regex

/^\S+$/g

Example

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"))                      
                       



回答2:


I suppose that you'll be using .test method on regex, /\s/g this one should do the job, it will return true if there's any space in the string. ex: /\s/g.test("String123/test") this will return false which means that the string is valid /\s/g.test("String123 /test) this will return true which means that the string is not valid



来源:https://stackoverflow.com/questions/42155576/regex-match-a-string-without-having-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!