JavaScript 字符串的endsWith()方法
endsWith()
方法如果字符串以指定的字符串结尾,则返回 true
。如果不是,则该方法返回 false
。
示例
// 字符串定义
let sentence = "Java is to JavaScript what Car is to Carpet.";
// 检查给定字符串是否以 "to Carpet." 结尾
let check = sentence.endsWith("to Carpet.");
console.log(check);
// 输出
// true
endsWith() 语法
endsWith()
方法的语法是:
str.endsWith(searchString, length);
这里,str 是一个字符串。
endsWith() 参数
endsWith()
方法接受两个参数:
- searchString - 在 str 末尾要搜索的字符。
- length (可选) - 用作搜索 searchString 的 str 的长度。默认值是
str.length
。
endsWith() 返回值
endswith()
方法返回:
true
- 如果在字符串末尾找到了给定的字符。false
- 如果在字符串末尾没有找到给定的字符。
示例 1:使用 endsWith() 方法
// 字符串定义
let sentence = "JavaScript is fun";
// 检查给定字符串是否以 "fun" 结尾
let check = sentence.endsWith("fun");
console.log(check);
// 检查给定字符串是否以 "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()
方法区分大小写。例如,
// 字符串定义
let sentence = "JavaScript is fun";
// 检查给定字符串是否以 "fun" 结尾
let check = sentence.endsWith("fun");
console.log(check);
// 检查给定字符串是否以 "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";
// 第二个参数指定要考虑的字符串部分
let check = sentence.endsWith("JavaScript", 10);
console.log(check);
输出
true;
在上述示例中,我们在使用 endswith()
方法时指定了要考虑的字符串部分。
我们传递了两个参数,"JavaScript"
和 10
,其中 "JavaScript"
表示要搜索的字符串,10
表示要考虑的字符串部分。
该方法检查字符串的前 10 个字符是否以 "JavaScript"
结尾,并返回 true
。