Alexander Mills
Alexander Mills

Reputation: 99980

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

Upvotes: 4

Views: 895

Answers (4)

Saleem
Saleem

Reputation: 8978

Try following regex:

/^(\S+\s?)+$/im.test(text)

where parameter text is whatever string you want to test.

OUTPUT:

  • a b cde f ghijk lm n <-- match
  • but reject <-- match
  • a b cd ef g <-- no match

See demo https://regex101.com/r/lS4cU7/2

Upvotes: 2

ak_
ak_

Reputation: 2815

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!

Upvotes: 4

Shafizadeh
Shafizadeh

Reputation: 10340

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+/

Upvotes: 5

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

If your tokens are just ASCII letters or digits, use

var regex = /^[a-z0-9]+(?:\s[a-z0-9]+)*$/i;

See the regex demo

The pattern matches:

  • ^ - the start of string
  • [a-z0-9]+ - one or more letters or digits
  • (?:\s[a-z0-9]+)* - 0+ sequences of:
    • \s - any whitespace, 1 symbol
    • [a-z0-9]+ - 0+ letters or digits
  • $ - end of string

This way, you restrict the number of spaces between "words" to just 1 occurrence.

If you plan to allow leading/trailing whitespace, add \s* after ^ and before $.

Upvotes: 1

Related Questions