var myStr = “ Earth is a beautiful planet ”;var myStr2 = myStr.trim();//==“Earth is a beautiful planet”;
if (myStr2.startsWith(“Earth”)) // returns TRUE
if (myStr2.endsWith(“planet”)) // returns TRUE
if (myStr.startsWith(“Earth”))// returns FALSE due to the leading spaces…
if (myStr.endsWith(“planet”))// returns FALSE due to trailing spaces…
的传统方式
function strStartsWith(str, prefix) {return str.indexOf(prefix) === 0;}
function strEndsWith(str, suffix) {return str.match(suffix+"$")==suffix;}
if(typeof String.prototype.endsWith !== "function") {/*** String.prototype.endsWith* Check if given string locate at the end of current string* @param {string} substring substring to locate in the current string.* @param {number=} position end the endsWith check at that position* @return {boolean}** @edition ECMA-262 6th Edition, 15.5.4.23*/String.prototype.endsWith = function(substring, position) {substring = String(substring);
var subLen = substring.length | 0;
if( !subLen )return true;//Empty string
var strLen = this.length;
if( position === void 0 )position = strLen;else position = position | 0;
if( position < 1 )return false;
var fromIndex = (strLen < position ? strLen : position) - subLen;
return (fromIndex >= 0 || subLen === -fromIndex)&& (position === 0// if position not at the and of the string, we can optimise search substring// by checking first symbol of substring exists in search position in current string|| this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false)&& this.indexOf(substring, fromIndex) === fromIndex;};}
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // truealert( str.endsWith("to be") ); // falsealert( str.endsWith("to be", 19) ); // true