0

Is there any way to find which input character fails the regex pattern.

For ex: consider [A-Za-z\s.&] is only allowable but the user enter like "test/string" where '/' invalidates input. How to find who fails regex (our case '/')

1
  • all answers are good. RoToRa perfectly matches my need. thank u Commented Apr 29, 2010 at 10:50

3 Answers 3

2

You could remove the valid chars and you'll have a string of the invalid ones:

var invalid = "test/string".replace(/[A-Za-z\s.&]/g,""); // results in "/"
Sign up to request clarification or add additional context in comments.

Comments

1

Just negate your character class and find out which character(s) match.

[^A-Za-z\s.&]

will match the / in test/string. So, altogether you get

if (/^[A-Za-z\s.&]+$/.test(subject)) {
    // Successful match
} else {
    result = subject.match(/[^A-Za-z\s.&]/g);
    // result is an array that contains all the characters that failed the match
}

Comments

1

To find which characters fails, split it with /[A-Za-z\s.&]+/, you will get invalid characters list

"test/string".split(/[A-Za-z\s.&]+/).join('')
/

To check username is valid or not, you could just use ^ and $ anchors.

/^[A-Za-z\s.&]+$/

1 Comment

I think he's got that part covered, but he wants to find out why the match failed, i. e. on which character.

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.