Confirm the Ending

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Confirm the Ending相关的知识,希望对你有一定的参考价值。

检查字符串结尾

判断一个字符串(str)是否以指定的字符串(target)结尾。

如果是,返回true;如果不是,返回false。

第一种,for循环,利用substr()截取字符串中的最后部分

function confirmEnding(str, target) {
  if ( str.substr(str.length-target.length , str.length) === target) {
    return true;
  }else {
    return false;
  }
}

confirmEnding("Bastian", "n");

第二种


function confirmEnding(str, target) {
  if ( str.substring(str.length-target.length , str.length) === target) {
    return true;
  }else {
    return false;
  }
}


第三种

confirmEnding("Bastian", "n");

function confirmEnding(str, target) { if ( str.slice(str.length-target.length , str.length) === target) { return true; }else { return false; } } confirmEnding("Bastian", "n");

三种方法都是截取字符串指定字段,其中slice()和substring()接收的是起始位置和结束位置(不包括结束位置),而substr接收的则是起始位置和所要返回的字符串长度.

还有在对负值的处理上,slice()会将它字符串的长度与对应的负数相加,结果作为参数;substr()则仅仅是将第一个参数与字符串长度相加后的结果作为第一个参数;substring()则干脆将负参数都直接转换为0

以上是关于Confirm the Ending的主要内容,如果未能解决你的问题,请参考以下文章