LoginSignup
3
0

More than 5 years have passed since last update.

js 文章の最後の文字とtargetの文字の真偽判定する

Last updated at Posted at 2016-12-11

文章の最後の文字とtargetの文字の真偽判定する方法

*.endsWith()は使わない。

script.js
function confirmEnding(str, target) {
 //write your code.
}
confirmEnding("Bastian", "n"); //true 


("Bastian", "n") //true
("He has to give me a new name", "name") //true
("Open sesame", "same") //true
("Walking on water and developing software from a specification are easy if both are frozen", "specification") //false

試したコード

script.js
function confirmEnding(str, target) {
  return str.substr(-target.length) === target;
}

考え方

targetの文字数を取得する
targetLengthの数だけ、strの文末からsliceで変数strEndにいれる。
strEndとtargetを比較する。

もっと簡潔に美しくかけるよ!という方、コメントお待ちしております。
閲覧ありがとうございました。

参考リンク

MDN Array.prototype.slice()

追記

gaogao_9さんのコメントを反映しました。

3
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0