JavaScript对象:JavaScript endsWith() 方法

返回到:JavaScript对象:JavaScript String 对象

定义和用法

endsWith() 方法用来判断当前字符串是否是以指定的子字符串结尾的(区分大小写)。

如果传入的子字符串在搜索字符串的末尾则返回 true,否则将返回 false。

所有主要浏览器都支持 endsWith() 方法

语法

string.endsWith(searchvalue, length)

参数值

参数描述
searchvalue必需,要搜索的子字符串。
length设置字符串的长度。默认值为原始字符串长度 string.length。

返回值

类型描述
String返回在指定位置的字符。

技术细节

返回值:布尔值,如果传入的子字符串在搜索字符串的末尾则返回true,否则将返回 false。
JavaScript 版本:ECMAScript 6

实例

设置不同字符串长度来判断:

var str = "To be, or not to be, that is the question.";
 
str.endsWith("question.");  // true
str.endsWith("to be");      // false
str.endsWith("to be", 19);  // true

DEMO:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web176教程(Web176.com)</title>
</head>
<body>

<h2>JavaScript 字符串</h2>

<p>如果传入的子字符串在搜索字符串的末尾则返回 true,否则将返回 false。</p>

<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p>注意: IE 11 及更早版本不支持 endsWith() 方法。</p>

<script>
let str = "To be, or not to be, that is the question.";
document.getElementById("demo").innerHTML = str.endsWith("question.");  // true
document.getElementById("demo1").innerHTML = str.endsWith("to be");      // false
document.getElementById("demo2").innerHTML = str.endsWith("to be", 19);  // true
</script>

</body>
</html>

作者:terry,如若转载,请注明出处:https://www.web176.com/javascriptbook/jsarrtips/2987.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年8月19日 下午4:32
下一篇 2021年8月19日 下午4:43

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注