JavaScript中的endsWith()方法是一种判断字符串是否以指定字符串结尾的方法,它返回一个布尔值,表示字符串是否以指定的字符串结尾。
使用方法
var str="hello world"; console.log(str.endsWith("world")); //true console.log(str.endsWith("World")); //false
endsWith()方法接受两个参数,第一个参数是要检查的字符串,第二个参数是可选的,表示从字符串的哪个位置开始检查,默认值为字符串的一个字符。
var str="hello world"; console.log(str.endsWith("world",10)); //true console.log(str.endsWith("world",5)); //false
endsWith()方法可以用于检查文件扩展名,例如检查文件是否为.png格式:
var filename="example.png"; console.log(filename.endsWith(".png")); //true
endsWith()方法也可以用于检查URL是否以指定字符串结尾:
var url="http://www.example.com/index.html"; console.log(url.endsWith("index.html")); //true
endsWith()方法是一种非常有用的字符串处理方法,可以帮助我们快速判断字符串是否以指定字符串结尾。