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

String.prototype.startsWith = 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".startsWith("Ch")); // true
alert("Chris".startsWith("cH")); // false
alert("Chris".startsWith("cH", true)); // true

1 Comment

Sergey · October 19, 2018 at 5:02 AM

It’s not an optimal solution. What if your string is very long? Or what if you are going to compare “İstanbul” with “ıstanbul”?

Leave a Reply

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