JavaScript String endsWith() 方法

定義和用法

如果字符串以規定字符串結尾,endsWith() 方法返回 true

否則返回 false

endsWith() 方法區分大小寫。

另請參閱:

startswith() 方法

實例

例子 1

檢查字符串是否以 "world" 結尾:

let text = "Hello world";
let result = text.endsWith("world");

親自試一試

let text = "Hello World";
let result = text.endsWith("world");

親自試一試

例子 2

檢查字符串的前 11 個字符是否以 "world" 結尾:

let text = "Hello world, welcome to the universe.";
text.endsWith("world", 11);

親自試一試

語法

string.endsWith(searchvalue, length)

參數

參數 描述
searchvalue 必需。要搜索的字符串。
length

可選。要搜索的字符串的長度。

默認值是字符串的長度。

返回值

類型 描述
布爾值 如果字符串以該值結尾,則為 true,否則為 false

瀏覽器支持

endsWith() 是 ECMAScript6 (ES6) 特性。

所有瀏覽器都支持 ES6 (JavaScript 2015):

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
支持 支持 支持 支持 支持

Internet Explorer 11(及更早版本)不支持 endsWith()。

相關頁面

JavaScript 字符串

JavaScript 字符串方法

JavaScript 字符串搜索