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
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+/
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With