0

I'm trying to do a regex which accepts a string containing 3-10 characters (white spaces before and after the string are allowed).

Why does this:

return (this.state.user.name.match(`^\s*([a-zA-Z0-9.\-_]{3,10})\s*$`));

returns false when I try to put white space(s) before and/or after the string? (it works correctly if I don't put white spaces.)

I am probably missing something, because it works using the regex tester: https://regex101.com/r/2371SM/1

Thanks for your help.

2
  • Are you sure that the variable has spaces and is not trimmed? Commented Apr 27, 2018 at 20:54
  • I allow spaces to trim it later. Commented Apr 27, 2018 at 20:55

1 Answer 1

3

When you pass the regex as a string you have to do double \\ so that you are escaping the \ and not the letter that follows it:

console.log(((" abcd").match(`^\\s*([a-zA-Z0-9.\-_]{3,10})\\s*$`)));

console.log(((" abcd").match(/^\s*([a-zA-Z0-9.\-_]{3,10})\s*$/)));

Sign up to request clarification or add additional context in comments.

1 Comment

You made my day. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.