文字列が与えられたターゲット文字列で終わるかどうかを調べる


  • がストリング(最初の引数、str)が与えられた目標ストリング(第2の引数target)で終わるかどうかチェックしてください.
  • この課題は、ES 2015で導入された.endsWith() methodで解決することもできます.
  • function confirmEnding(str, target) {
      return str;
    }
    
    confirmEnding("Bastian", "n");
    
    まず、substrを学びましょう.
    let sentence = "I'm running in 5 minutes.";
    console.log(sentence.substr(2)); // would return "m running in 5 minutes". If (0,5) it would give me the letters that start at 0 and end at 5 not including 5.
    // If we're trying to find the end parts of the sentence simply.
    console.log(sentence.substr(-2); // would display "s."
    // also could be done with endsWith()
    if (str.endsWith(target)) {
      return true;
    }
     return false;
    };
    
    回答
    function confirmEnding(str, target) {
      if (str.substr(-target.length) === target) {
        return true;
      } else {
        return false;
     }
    }
    
    console.log(confirmEnding("Bastian", "n")); // will display true