Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add startsWith in IE 11

IE 11 does not support startsWith with strings. (Look here)

How do you add a prototype so that it supports the method?

like image 485
Sandah Aung Avatar asked Mar 25 '16 03:03

Sandah Aung


1 Answers

Straight from the MDN page, here's the polyfill:

if (!String.prototype.startsWith) {     Object.defineProperty(String.prototype, 'startsWith', {         value: function(search, rawPos) {             var pos = rawPos > 0 ? rawPos|0 : 0;             return this.substring(pos, pos + search.length) === search;         }     }); } 

This is safe to use in any browser. If the method already exists, this code will see that and do nothing. If the method does not exist, it will add it to the String prototype so it is available on all strings.

You just add this to one of your JS files in some place where it executes at startup and before you attempt to use .startsWith().

If you want a polyfill version that follows the specification in its entirety, including all possible error checks, you can get that here, but you will probably have to use that with a bundler in the browser because of the way the polyfill is spread out among several files.

like image 185
jfriend00 Avatar answered Sep 24 '22 04:09

jfriend00