JavaScript 檢查字串1是否以字串2結尾
我們需要編寫一個 JavaScript 函式,該函式接收兩個字串,比如 string1 和 string2,並確定 string1 是否以 string2 結尾。
例如,
"The game is on" Here, "on" should return true
儘管
"the game is off" Above, “of" should return false
讓我們編寫此函式的程式碼:
示例
const first = 'The game is on';
const second = ' on';
const endsWith = (first, second) => {
const { length } = second;
const { length: l } = first;
const sub = first.substr(l - length, length);
return sub === second;
};
console.log(endsWith(first, second));
console.log(endsWith(first, ' off'));輸出
控制檯中的輸出將是
true false
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP