Search code examples
javascriptregexwhitespace

Js regex character set including " " or ""


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?


Solution

  • 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 ?.