5
var s = "Main String";
s.startsWith("Main");

Replacing startWith with a similar logic or any other method generic to all browsers.

Chetan Raikwal
  • 138
  • 1
  • 1
  • 9

2 Answers2

16

A good replacement for startsWith would be using s.substring(0, 4) == 'Main'

This should work, so go ahead and try it.

Addisonep
  • 195
  • 1
  • 5
4

Add a prototype method in String:

String.prototype.myStartsWith = function(str){
 if(this.indexOf(str)===0){
  return true;
 }else{
   return  false;
 }
};

Now call:

s.myStartsWith("Main");
Tuhin
  • 3,335
  • 2
  • 16
  • 27
  • Is the reason against doing this that it's not as efficient as the other solution? – Marcus Mar 19 '18 at 19:34
  • Remenber to check if exist before overwrite: `if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position){ return this.substr(position || 0, searchString.length) === searchString; }; }` – Juanmabs22 Jan 29 '21 at 13:51