endsWith()
方法如果字符串以指定的字符串结尾,则返回 true
。否则,该方法返回 false
。
示例
// string definition
let sentence = "Java is to JavaScript what Car is to Carpet.";
// checking if the given string ends with "to Carpet."
let check = sentence.endsWith("to Carpet.");
console.log(check);
// Output
// true
endsWith() 语法
endsWith()
方法的语法是:
str.endsWith(searchString, length)
其中,str 是一个字符串。
endsWith() 参数
endsWith()
方法接受 **两个** 参数:
- searchString - 要在 str 末尾搜索的字符。
- length (可选) - 在其中搜索 searchString 的 str 的长度。默认值为 str.length。
endsWith() 返回值
endswith()
方法返回:
-
true
- 如果在字符串末尾找到了给定的字符。 -
false
- 如果在字符串末尾未找到给定的字符。
示例 1:使用 endsWith() 方法
// string definition
let sentence = "JavaScript is fun";
// checking if the given string ends with "fun"
let check = sentence.endsWith("fun");
console.log(check);
// checking if the given string ends with "is"
let check1 = sentence.endsWith("is");
console.log(check1);
输出
true false
在上面的示例中,我们使用 endsWith()
方法来检查 sentence 是否以指定的字符串结尾。
由于字符串 "JavaScript is fun"
以 "fun"
结尾,因此 sentence.endsWith("fun")
返回 true
。
sentence.endsWith("is")
返回 false
,因为给定的字符串不是以 "is"
结尾。
示例 2:endsWith() 用于区分大小写的字符串
endsWith()
方法区分大小写。例如:
// string definition
let sentence = "JavaScript is fun";
// checking if the given string ends with "fun"
let check = sentence.endsWith("fun");
console.log(check);
// checking if the given string ends with "Fun"
let check1 = sentence.endsWith("Fun");
console.log(check1);
输出
true false
在这里,我们正在检查 sentence
是否以 "fun"
或 "Fun"
结尾。
由于 endsWith()
方法区分大小写,它将 "fun"
和 "Fun"
视为两个不同的字符串。因此,该方法返回 "fun" 的 true
和 "Fun" 的 False
。
示例 3:endsWith() 带有两个参数
let sentence = "JavaScript is fun";
// second argument specifies the portion of string to consider
let check = sentence.endsWith("JavaScript", 10);
console.log(check);
输出
true
在上面的示例中,我们在使用 endswith()
方法检查指定的 searchString 时,指定了要考虑的字符串部分。
我们传递了两个参数,"JavaScript"
和 10
,其中 "JavaScript"
表示要搜索的字符串,10
表示要考虑的字符串部分。
该方法检查字符串的前 **10** 个字符是否以 "JavaScript"
结尾,并返回 true
。
另请阅读