Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex .test(): Returning true for a double space (or more) in the string?

My goal is to return 'true' for a valid string, which in this case is a string that starts with a letter, then has any combination of letters and numbers and spaces, but no consecutive spaces.

I've tried several combinations, with the following 'prefix':

^[a-zA-Z][a-zA-Z0-9]*$

This works just fine for the 'start with a letter' and 'combinations of letters and numbers', but I am having trouble adding the regex to match a space, and only a single space.

For example:

^[a-zA-Z][a-zA-Z0-9]*$|[\s{0,1}]

doesn't work. It will return true for "asdasdasd 3333$", among other things.

It is if I am trying to force the logic:

if (firstLetter != letter){
    return false;
}
else{
    var spaceFound = false;
    for ( var int = 0; int < individualLetters.length; int++) {
            if (individualLetters[int] == space){
                  if (spaceFound == true){
                         return false; 
                  }
                  else {
                          spaceFound = true;     
                  }  
            }
        if(individualLetters[int] != letterOrNumber){
                      return false;
            }
            else{
                spaceFound = false;
                continue; 
            }  
    }
}

However I think I am missing a fundamental understanding on regex. Any way, any help would be appreciated.

like image 746
Danedo Avatar asked Mar 10 '26 12:03

Danedo


1 Answers

Here are two different flavors is one flavor:

function test(s) {
    return /^[A-Z]([A-Z]|\d| (?! ))*$/i.test(s);
}

http://jsfiddle.net/HCNDD/2

like image 58
Ates Goral Avatar answered Mar 13 '26 01:03

Ates Goral