Js regex character set including " " or ""

Viewed 47

I want to check if there is a y after x my code:

let STR = "x y"
console.log(/xy/g.test(STR) || /x y/g.test(STR))

this is working but to make the code better, I want to combine /xy/g with /x y/g to get one regex but how?

2 Answers

You could test for an optional (0 or 1 occurrences) of space between x and y by using the ? metacharacter:

let STR = "x y"
console.log(/x( )?y/g.test(STR))

If you meant to test for an arbitrary number of spaces, use * instead of ?.

const isValid = str => /x\s?y/g.test(str);

console.log( isValid('x y') );
console.log( isValid('xy') );
console.log( isValid('xzy') );

If you want to consider 1+ spaces: \s*

Related