Confirm the Ending--freecodecamp算法题目

Confirm the Ending(检查字符串结尾)

  1. 要求
    • 判断一个字符串(str)是否以指定的字符串(target)结尾。
    • 如果是,返回true;如果不是,返回false。
  2. 思路
    • 利用.replace(/[\W]/g,'')去除字符串中多余(/[\W]/g  匹配任何非单词字符,即只要不是a-z、A-Z、0-9和_)。
    • 在for循环中用.substr(-i,i)选出各种长度的结尾与target对比,发现相等返回true,反之返回false
  3. 代码
    •  1 function confirmEnding(str, target) {
       2   // 请把你的代码写在这里
       3   var temp = str.replace(/[\W]/g,'');
       4   for (var i=1;i<temp.length;i++){
       5     if (temp.substr(-i,i) == target){
       6       temp = 'yes';
       7     }
       8   }
       9   return temp == 'yes';
      10 }
      11 
      12 confirmEnding("Bastian", "n");
  4. 相关链接
    • https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substr

猜你喜欢

转载自www.cnblogs.com/ahswch/p/9292994.html