ES6 now supports the startsWith()
and endsWith()
method for checking beginning and ending of string
s. If you want to support pre-es6 engines, you might want to consider adding one of the suggested methods to the String
prototype.
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.match(new RegExp("^" + str));
};
}
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str) {
return this.match(new RegExp(str + "$"));
};
}
var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo"); // true