tatty27 tatty27 - 3 months ago 9
Javascript Question

Get list of words containing substring in string

I have a script that runs if a value entered contains the substring 'sn' but I need it to ignore any instances of that substring if they are immediately followed by either the letter t or an apostrophe.

The reason for this is that the value entered contains the serial number of a device and the script can pick the serial number out because it is preceded by the letters 'sn'. The problem is that if the user enters words such as "wasn't" or "isn't" (can be with or without the apostrophe depending on who entered it) the script gets the last instance of 'sn'. I need it to completely ignore those words.

The code I use to check for 'sn' is...

var lowercase_name = subject.toLowerCase();
var has_sn = lowercase_name.indexOf("sn") > -1;
if(has_sn === true){
//do something
}

Answer

To do something like that with string, indexOf not good enough since you cannot have exception. What good enough though is a regexp. Your condition is "ignore any instances of that substring if they are immediately". That mean that you should use a negative look ahead ((?!)).

In your case, the good regexp shoud be :

var lowercase_name = subject.toLowerCase();
var has_sn = lowercase_name.match(/sn(?!['t])/);
if(has_sn){
    //do something
}
  • (?!) = negative look ahead. Search for sn not followed by what's inside after the !
  • [] = "or" character. Match any of the character inside the brackets.

Now, if you want to make more complex task, you should take a look at some regexp tutorials