108

How do I use a javascript regular expression to check a string that does not match certain words?

For example, I want a function that, when passed a string that contains either abc or def, returns false.

'abcd' -> false

'cdef' -> false

'bcd' -> true

EDIT

Preferably, I want a regular expression as simple as something like, [^abc], but it does not deliver the result expected as I need consecutive letters.

eg. I want myregex

if ( myregex.test('bcd') ) alert('the string does not contain abc or def');

The statement myregex.test('bcd') is evaluated to true.

Soviut
  • 83,904
  • 44
  • 175
  • 239
bxx
  • 1,611
  • 2
  • 12
  • 16

6 Answers6

165

This is what you are looking for:

^((?!(abc|def)).)*$

The ?! part is called a negative lookahead assertion. It means "not followed by".

The explanation is here: Regular expression to match a line that doesn't contain a word

Matthias
  • 11,072
  • 8
  • 38
  • 56
ssgao
  • 4,661
  • 5
  • 33
  • 49
  • 1
    This is the answer I expect! Thanks. I need a regular expression rather than a function. My question was edited and answers came up to answer the new version of my question. This is why I used an "EDIT" part to avoid confusion. – bxx Mar 21 '13 at 03:53
  • 2
    Is there an answer that doesn't match a whole word? Your example "abc", "babc" and "abcd" all fail and where as "xyz" passes. I need "abc" to fail but "abcd" to pass. Removing the `.` and `*` don't seem to work – gman Jan 02 '17 at 17:15
23
if (!s.match(/abc|def/g)) {
    alert("match");
}
else {
    alert("no match");
}
Petar Ivanov
  • 88,488
  • 10
  • 77
  • 93
7

Here's a clean solution:

function test(str){
    //Note: should be /(abc)|(def)/i if you want it case insensitive
    var pattern = /(abc)|(def)/;
    return !str.match(pattern);
}
NoBrainer
  • 5,576
  • 1
  • 26
  • 26
2
function test(string) {
    return ! string.match(/abc|def/);
}
Flimzy
  • 68,325
  • 15
  • 126
  • 165
1

This can be done in 2 ways:

if (str.match(/abc|def/)) {
                       ...
                    }


if (/abc|def/.test(str)) {
                        ....
                    } 
Girish Gupta
  • 1,143
  • 11
  • 27
1
function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}
Bemmu
  • 17,091
  • 16
  • 73
  • 92