ECMAScript6学习笔记《三》-----“包含字符串的三种新方法”
2015-08-22 21:58
435 查看
以前,JavaScript只有 indexOf 方法,可以用来确定一个字符串是否包含在另一个字符串中,
如今:
includes():返回布尔值,表示是否找到了参数字符串。
startsWith():返回布尔值,表示参数字符串是否在源字符串的头部。
endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部。
下面代码表示,使用第二个参数n时,endsWith 的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<header>
<!-- 加载Traceur编译器 -->
<script src="http://google.github.io/traceur-compiler/bin/traceur.js" type="text/javascript"></script>
<!-- 将Traceur编译器用于网页 -->
<script src="http://google.github.io/traceur-compiler/src/bootstrap.js" type="text/javascript"></script>
<!-- 打开实验选项,否则有些特性可能编译不成功 -->
<!-- <script>
traceur.options.experimental = true;
</script> -->
<script type="module">
var str = "Hello world!";
// str.startsWith("Hello") // true
// str.endsWith("!") // true
// str.includes("o") // true
const name = "fengliya ni hao a!";
// alert(name.startsWith("ni"));
// alert(name.endsWith("!"));
// alert(name.includes("hao"));
alert(name.startsWith("ni",9)); // true 从第9位开始到结束是不是“ni”(不包含)
alert(name.endsWith("y",7)); // true 前7个字符的末尾是不是包含 “y”
alert(name.includes("fengliya",2)); //false 从第二位开始到结束是否包含“fengliya”
</script>
</header>
</head>
<body>
</body>
</html>
如今:
includes():返回布尔值,表示是否找到了参数字符串。
startsWith():返回布尔值,表示参数字符串是否在源字符串的头部。
endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部。
下面代码表示,使用第二个参数n时,endsWith 的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<header>
<!-- 加载Traceur编译器 -->
<script src="http://google.github.io/traceur-compiler/bin/traceur.js" type="text/javascript"></script>
<!-- 将Traceur编译器用于网页 -->
<script src="http://google.github.io/traceur-compiler/src/bootstrap.js" type="text/javascript"></script>
<!-- 打开实验选项,否则有些特性可能编译不成功 -->
<!-- <script>
traceur.options.experimental = true;
</script> -->
<script type="module">
var str = "Hello world!";
// str.startsWith("Hello") // true
// str.endsWith("!") // true
// str.includes("o") // true
const name = "fengliya ni hao a!";
// alert(name.startsWith("ni"));
// alert(name.endsWith("!"));
// alert(name.includes("hao"));
alert(name.startsWith("ni",9)); // true 从第9位开始到结束是不是“ni”(不包含)
alert(name.endsWith("y",7)); // true 前7个字符的末尾是不是包含 “y”
alert(name.includes("fengliya",2)); //false 从第二位开始到结束是否包含“fengliya”
</script>
</header>
</head>
<body>
</body>
</html>
相关文章推荐
- 教你用Inkspace提取pdf中的矢量图【超详细】
- Object -C self -- 笔记
- linux下whoami,who,w学习
- Android——WebView方式开发web App
- C# 之 FTP服务器中文件上传与下载(一)
- Android——WebView方式开发web App
- spring JDBC 查询没有目标的方法
- 完整的图片去噪代码(python)
- Cocos2d-x3.1中使用万普平台实现Android平台广告添加
- 一步一步实现iOS应用PUSH功能
- 位图读、写、显示的C++实现实例
- 数组的简单算法
- Netty5中使用LineBasedFrameDecoder解决TCP粘包问题
- find命令的用法
- Android之——Fragment控制切换多个页面
- 在Cocos2dx项目中嵌入百度广告Android SDK
- BestCoder Round #52 (div.2) HDU 5418 Victor and World (DP+状态压缩)
- 使用资源组快速浏览跨region资源
- 人生需要拆穿(读书笔记)
- Android消息机制分析