Created
January 2, 2015 13:45
-
-
Save karl-gustav/8918f0195bb61ff801c6 to your computer and use it in GitHub Desktop.
Highly performant ES6 String extras polyfills for modern browsers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (!('startsWith' in String.prototype)) | |
Object.defineProperty(String.prototype, 'startsWith', { | |
value: function (searchString, position) { | |
if (Object.prototype.toString.call(searchString) === "[object RegExp]") | |
throw new TypeError("The search string cannot be a regular expression."); | |
if (position === undefined) | |
position = 0; | |
else | |
position = Math.min(Math.max(position, 0), this.length); | |
return this.lastIndexOf(searchString, position) === position; | |
}, | |
configurable: true, writable: true, | |
}); | |
if (!('endsWith' in String.prototype)) | |
Object.defineProperty(String.prototype, 'endsWith', { | |
value: function (searchString, endPosition) { | |
if (Object.prototype.toString.call(searchString) === "[object RegExp]") | |
throw new TypeError("The search string cannot be a regular expression."); | |
if (endPosition === undefined) | |
endPosition = this.length; | |
else | |
endPosition = Math.min(Math.max(endPosition, 0), this.length); | |
var start = endPosition - searchString.length; | |
if (start < 0) return false; | |
return this.indexOf(searchString, start) === start; | |
}, | |
configurable: true, writable: true, | |
}); | |
if (!('contains' in String.prototype)) | |
Object.defineProperty(String.prototype, 'contains', { | |
value: function (searchString, position) { | |
if (Object.prototype.toString.call(searchString) === "[object RegExp]") | |
throw new TypeError("The search string cannot be a regular expression."); | |
if (position === undefined) | |
position = 0; | |
else | |
position = Math.min(Math.max(position, 0), this.length); | |
return this.indexOf(searchString, position) !== -1; | |
}, | |
configurable: true, writable: true, | |
}); | |
if (!('repeat' in String.prototype)) | |
Object.defineProperty(String.prototype, 'repeat', { | |
value: function (count) { | |
if (count < 0 || count === Infinity) | |
throw new RangeError("The number of times the string is to be repeated must be in [0, Infinity)."); | |
if (count === 0) | |
return ''; | |
else if (count === 1) | |
return this.valueOf(); | |
var result = '', pattern = this; | |
for (;;) { | |
if (count & 1) result += pattern; | |
if (count >>= 1) pattern += pattern; | |
else return result; | |
} | |
}, | |
configurable: true, writable: true, | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied from http://www.snip2code.com/Snippet/69036/Highly-performant-ES6-String-extras-poly