tatty27 tatty27 - 7 months ago 23
Javascript Question

jQuery check if string if preceded with other letters

I need to detect if a value in an input contains the letters 'sn' followed by a hyphen (not immediately, the input will be sn12345 - more text) and if it does, then run a function which works fine unless the user enters words such as "isn't" or "wasn't".

Is there a way that I can detect if there are any letters before "sn" and whether or not to run the function. I did consider checking for the apostrophe but some users are quite lazy when entering into the input in question and don't use them.

var lowercase_name = subject.toLowerCase();
var has_sn = lowercase_name.indexOf("sn") > -1;
if(has_sn === true){
var has_hyphen = lowercase_name.indexOf("-") > -1;
if(has_hyphen === false){
//alert user missing hyphen
};
return false;
}
}


I did also consider checking if the "sn" is preceded by a space but if it is used at the beginning of the input (which it most likely will in this instance) that will fail.

Answer

Since you say there may or may not be spaces between sn and your dash, and you want to NOT match cases where sn is preceded by other letters, you could use a regex like:

var lowercase_name = subject.toLowerCase();
var has_sn = lowercase_name.indexOf("sn") > -1;
    if(has_sn === true){
        var snIsNotPrecededByLetters = lowercase_name.match(/\bsn/g);
        var has_hyphen = lowercase_name.indexOf("-") > -1;
            if(has_hyphen === false){
                //alert user missing hyphen
            };
                return false;
            }
    }

The "\b" in the Regex String makes it only match the "sn" if no letters precede it.