W3Cschool初级脚本算法(8.确认末尾字符算法挑战)

确认末尾字符算法挑战


问题:

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

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

这个挑战可以通过在ES2015中引入的.endsWith()方法来解决。但是出于这个挑战的目的,我们希望您使用JavaScript子串方法之一。


要求:

confirmEnding("Bastian", "n") 应该返回 true.

confirmEnding("Connor", "n") 应该返回 false.

confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") 应该返回 false.

confirmEnding("He has to give me a new name", "name") 应该返回 true.

confirmEnding("He has to give me a new name", "me") 应该返回 true.

confirmEnding("He has to give me a new name", "na") 应该返回 false.

confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") 应该返回 false.

 


问题答案:

function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
  var arr = str.replace(/\s+/g, "");
  var bb = arr.substr(arr.length - target.length, arr.length);
  if (bb == target) return true;
   
  return false;
}

confirmEnding("Bastian", "n");

 


题目链接:

https://www.w3cschool.cn/codecamp/confirm-the-ending.html

猜你喜欢

转载自blog.csdn.net/qq_42044073/article/details/82388818
今日推荐