Проверьте, заканчивается ли строка (первый аргумент,
str
) заканчивается данной целевой строкой (второй аргумент,target
).Эта проблема также может быть решена с помощью
.endswith () Метод
, который был введен в ES2015.
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
Оригинал: «https://dev.to/rthefounding/confirm-the-ending-11a4»