检查字符串是否以给定的目标字符串结束JavaScript的 [英] Check if string ends with the given target strings | javascript

查看:94
本文介绍了检查字符串是否以给定的目标字符串结束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).

这篇关于检查字符串是否以给定的目标字符串结束JavaScript的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆