检查字符串是否以给定的目标字符串结束JavaScript的

检查字符串是否以给定的目标字符串结束JavaScript的

问题描述:

我正在尝试编写javascript代码,测试第一个字符串的结尾是否与目标相同,返回true。否则,返回false。必须使用.substr()来获得结果。

I am trying to write javascript code that will test if the end of the first string is the same as the target, return true. Else, return false. must use .substr() to obtain the result.

function end(str, target) {
myArray = str.split();
//Test if end of string and the variables are the same
if (myArray.subsrt(-1) == target) {
 return true;
}
else {
 return false;
}
}

end('Bastian', 'n');


尝试:

function end(str, target) {
   return str.substring(str.length-target.length) == target;
}

更新

在新的浏览器中,您可以使用: string.prototype.endsWith ,但IE需要填充(您可以使用 https:// polyfill .io 包含polyfill并且不会为现代浏览器返回任何内容,它对于与IE相关的其他内容也很有用。

In new browsers you can use: string.prototype.endsWith, but polyfill is needed for IE (you can use https://polyfill.io that include the polyfill and don't return any content for modern browsers, it's also usefull for other things related to IE).