碎片时间学编程「350]:字符串以子字符串结尾

检查给定字符串是否以另一个字符串的子字符串结尾。
使用 for...in 循环和 String.prototype.slice() 方法从末尾开始获取给定单词的每个子字符串。
使用 String.prototype.endsWith() 方法根据文本检查当前子字符串。
如果找到,则返回匹配的子字符串。否则,返回未定义。
JavaScript
const endsWithSubstring = (text, word) => { for (let i in word) { const substr = word.slice(0, i + 1); if (text.endsWith(substr)) return substr; } return undefined;};
示例:
endsWithSubstring('Lorem ipsum dolor sit amet<br /', '<br />'); // '<br /'
更多内容请访问我的网站:https://www.icoderoad.com