The following is a quick JavaScript function which can determine if a string contains a substring:


String.prototype.contains = function(str, ignoreCase) {
  return (ignoreCase ? this.toUpperCase() : this)
    .indexOf(ignoreCase ? str.toUpperCase() : str) >= 0;
};

The above function is a function that, once defined, will exist for every string. The first parameter, which is the string to be found, is required. The second parameter, which is a boolean specifying to ignore casing if true, is not required and defaults to false. Here are some examples of how to use the above function:


alert("Chris".contains("hr")); // true
alert("Chris".contains("Hr")); // false
alert("Chris".contains("Hr", true)); // true

Leave a Reply

Your email address will not be published. Required fields are marked *