0

I am trying to create a regular expression in JavaScript which contains all alphabet, % and _. I have written this regex for that which is not working fine. Can anyone help me with this?

Here is my Regex:

^[^.<>(){}'&@#]*$
2
  • Why do you use a character class to exclude a random set of symbols instead of "translating" your actual requirement into an regular expression? Commented Jan 13, 2021 at 6:57
  • Also, "not working fine" is not a useful description of a problem. What do you want to do, what is the text, what do you expect to happen and what is happening instead? Commented Jan 13, 2021 at 6:59

1 Answer 1

2

Here is the regex you are looking for:

const regex = /[A-Za-z_%]/g

Explanation:
/.../ - Javascript regex literal syntax
[...] - A group of possible matches (exp. A or B or C etc.)
A-Za-z - Every English letter. (Upper & lower case)
_ - Underscore char
% - The % char.
g - Global flag suffix to keep matching every res.

You can try it in Regex tester

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

5 Comments

but if You add numbers it is also taking that, that has to be avoided.
It's working fine, but I am using this regex in angular Validators.pattern("/[A-Za-z_%]/g"), in that case it doesn't work properly, can you just let me know why?
@Ashwanikumar It's not a String, it is a regular expression. It's literals are the forward-slashes /PATTERN/, whereas the String literals are the quotes 'String'/"String".
@Ashwanikumar what Oskar said is correct but I'm not sure it's clear. Remove the "" and use it like: Validators.pattern(/[A-Za-z_%]/g)
I Added like this Validators.pattern("[A-Za-z_%]") it's working fine Thankyou.

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.