11

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.

3
  • Is it only the space you want to reject or there is another characters? Commented Feb 10, 2017 at 9:18
  • 1
    console.log(!(/\s/.test('this is'))); This would be the case Commented Feb 10, 2017 at 9:20
  • regex101.com/r/9gvVmm/1 Commented Feb 10, 2017 at 9:21

2 Answers 2

19

You may use \S

\S matches any non white space character

Regex

/^\S+$/

Example

function CheckValid(str){
   re = /^\S+$/
   return re.test(str)
 }


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

Sign up to request clarification or add additional context in comments.

2 Comments

@Justin please accept the answer if it solved the problem
In Sublime Text it'll be (^\S+$)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.