1

I have a case where I need to find if a string exactly does not match a word using regex in javascript.

I was trying negative lookahead.

var reg = /(?!(^Hello$))/
var a = "Hello";
var b = "something else";


console.log(reg.test(a)) // I need this to be false
console.log(reg.test(b)) // I need this to be true

How can I achieve this? In Javascript both the console log is giving true

Pang
  • 9,564
  • 146
  • 81
  • 122
prakash
  • 13
  • 3

1 Answers1

1

The problem is that you are not anchoring the entire regexp, so it can match at any point in the input string. It won't match right at the beginning, but it will match after the 'H', because there is no string matching (?!(^Hello$)) which follows the 'H', thereby satisfying the negative look-ahead.

To make your regexp do what you want, anchor it:

var reg = /^(?!Hello$)/;
  • Thank you.. that works. We have a config file where we specify the regex to validate the input. Another way is to add new validator like "not match". I was trying to use the existing regex validator to implement this. – prakash Dec 16 '16 at 08:53
  • 1
    @prakash If this is going to need to work with user-entered data you're going to need to consider how to escape any regex special characters in the matched string. For example, what if they want to match "not `$0.00`"? I would think it would be far quicker and more reliable to implement a not-equals that doesn't use regex. – PMV Dec 16 '16 at 23:38