Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS regex to match character string with maximum 1 space between tokens

I am pattern matching some strings to see if they match -

I want to accept

a b cde f ghijk lm n

but reject

a b    cd   ef g

since the latter has more than one whitespace character between tokens

I have this regex

new RegExp('^[a-zA-Z0-9\s?]+$', 'ig')

but it doesn't currently reject strings with more than 1 whitespace character between.

Is there any easy way to augment my current regex?

thanks

like image 480
Alexander Mills Avatar asked Sep 03 '25 14:09

Alexander Mills


2 Answers

Try this approach:

var str = "a b cde f ghijk lm n";
if(str.match(/\s\s+/)){
   alert('it is not acceptable');
} else {
   alert('it is acceptable');
}

Note: As @Wiktor Stribizew mentioned in the comment, maybe OP wants to reject string containing some symbols like this $. So it would be better to use this regex in the condition:

/[^a-zA-Z0-9\s]|\s\s+/
like image 148
Shafizadeh Avatar answered Sep 05 '25 03:09

Shafizadeh


Must you use regex? Why not just check to see if the string has two spaces?

JavaScript

strAccept = "a b c def ghijk lm n";
strReject = "a b    cd   ef g";


function isOkay(str) {
    return str.indexOf('  ') == -1 && str.indexOf(' ') >= 0;
}


console.log(isOkay(strAccept))
console.log(isOkay(strReject))

Output

true
false

JS Fiddle: https://jsfiddle.net/igor_9000/ta216m3v/1/

Hope that helps!

like image 38
Adam Konieska Avatar answered Sep 05 '25 04:09

Adam Konieska