0

I have a string and two words from a dictionary and I am trying to know if in my string there are words that are not my dictionary words.

var string = 'foobarfooba';
var patt = new RegExp("[^(foo|bar)]");// words from dictionary
var res = patt.test(string);
console.log(res);//return false

It should return true because in my string there is also 'ba', but it return false.

asked Jun 18, 2015 at 23:16
2
  • 1
    Lose the square brackets. You're not looking for a character class Commented Jun 18, 2015 at 23:17
  • var patt = /foo|bar/; Commented Jun 18, 2015 at 23:18

1 Answer 1

1

Same as Phil commented in your question, you have to get rid of the character class:

[^(foo|bar)]
^-- here --^

Character classes are used to match (or not match if you use ^) specific unsorted characters.

Just use:

var patt = new RegExp("(?:foo|bar)");// words from dictionary

If you want to ensure that all the string matches your regex, you can use:

^(?:foo|bar)+$

Working demo

If you want to capture the invalid words, you can use a regex with capturing groups like this:

^(?:foo|bar)+|(.+)$

Working demo

Match information

MATCH 1
1. [9-11] `ba`
answered Jun 18, 2015 at 23:19
Sign up to request clarification or add additional context in comments.

10 Comments

But I need to know if there are some string like 'ba' that is different of my word
it still returns false
@Giuseppefederico that's ok, it returns false because there are words not matching your regex. Isn't it what you want?
Maybe I didn't explain well, I need to know that there is 'ba' that it is not in my regex
I am sorry you are right, could you explain me the meaning of ?: and +$
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.