4

I am trying to find a way to determine which character in my string does not match the regex, is there a way to do so in Javascript?

I've been using the regex object and i was able to determine whether a string matches the regex but i would like to go step further to determine why a string does not match the regex.

any thoughts?

This was what I currently have ... i am just trying to make sure a string only contains the set of characters found in the following regex ... and i would like to see which character does not match.

Here's my code :

var regexTest = new RegExp("^[0-9a-zA-Z\\!\\040\\@\\s\\#\\$\\%\\&\\*\\(\\)\\_\\+\\:\\\"\\<\\>\\?\\-\\=\\;\\'\\,\\.\\\\]+$",g); var bValid = regexTest.test(value); //this will check whether the value is valid ... 

I've tried using value = value.replace(regexTest,''), but was unable to actually filter out the characters.

1
  • 3
    I don't think this is really well defined in general. Which character in "aababb" doesn't match the regex /^a*b*$/? Which character in "aaaccc" doesn't match the regex /^a+b+c+$/? Which character in "" (ie: the empty string) doesn't match the regex /a+/? Commented Feb 9, 2012 at 17:14

1 Answer 1

6

You could replace all the characters that do match with '', leaving only the things that don't match:

'abc123'.replace(/([a-z]+)/g, '') // "123" 
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, you meant catch the unmatched terms. Apologies, I misread. The above will sort your problem
This doesn't seem to quite work - i've edited the question for some more clarity.
What does your huge regex do? Can you provide a test string?
I did - just updated the question. Eventually decided to check the string one character as a time - don't think that's too nice of a solution but works for now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.