第二章 字符串与正则表达式(深入理解ES6)

一、字符串的方法

JS 字符串的特性总是落后于其它语言,直到 ES5 中字符串才获得了 trim() 方法。 而 ES6 则继续添加新功能以扩展 JS 解析字符串的能力。
**startsWith()**方法:给定文本出现在字符串起始处返回true,
**endsWith()**方法:给定文本出现在字符串结尾位置处返回true,
**includes()**方法:给定文本存在字符串中的任意位置时返回true

	var msg = "Hello world!"; 
	
	console.log(msg.startsWith("Hello")); // true 
	console.log(msg.endsWith("!")); // true 
	console.log(msg.includes("o")); // true 
	
	console.log(msg.startsWith("o")); // false 
	console.log(msg.endsWith("world!")); // true 
	console.log(msg.includes("x")); // false 
	
	
	// 空格也算一个字符
	console.log(msg.startsWith("o", 4)); // true  从 msg 字符串的索引位置 4 (即 "Hello" 中的 "o" )开始尝试匹配
	console.log(msg.endsWith("o", 8)); // true   从位置 4 开始搜索,因 为参数 8 会从字符串的长度值( 12 )中被减去
	console.log(msg.includes("o", 8)); // false  从索引 位置 8 开始尝试匹配,也就是 "world" 中的 "r"
	

如果向 startsWith() 、 endsWith() 或 includes() 方法传入了正则表达式而不是字符 串,会抛出错误。这与 indexOf() 以及 lastIndexOf() 方法的表现形成了反差,它们会 将正则表达式转换为字符串并搜索它

**repeat()**方法:接受一个参数作为字符串的重复次数,返回 一个将初始字符串重复指定次数的新字符串。


	console.log("x".repeat(3)); // "xxx" 
	console.log("hello".repeat(2)); // "hellohello" 
	console.log("abc".repeat(4)); // "abcabcabcabc"
	

二、复制正则表达式

你在 ES5 环境中运行这段代码,那么你会收到一条错误信息,表示在第一个参数已经是 正则表达式的情况下不能再使用第二个参数。 ES6 则修改了这个行为,允许使用第二个参 数,并且让它覆盖第一个参数中的标志。

	var re1 = /ab/i, // ES5 中会抛出错误, ES6 中可用 
	re2 = new RegExp(re1, "g");

	console.log(re1.toString()); // "/ab/i" 
	console.log(re2.toString()); // "/ab/g" 
	
	console.log(re1.test("ab")); // true 
	console.log(re2.test("ab")); // true 
	
	console.log(re1.test("AB")); // true 
	console.log(re2.test("AB")); // false
	

三、模板字面量

模板字面量是 ES6 针对 JS 直到 ES5 依然完全缺失的如下功能的回应:
多行字符串:针对多行字符串的形式概念;
基本的字符串格式化:将字符串部分替换为已存在的变量值的能力;
HTML 转义:能转换字符串以便将其安全插入到 HTML 中的能力。

模板字面量的最简单语法,是使用反引号( ` )来包裹普通字符串,而不是用双引号或单 引号。参考以下例子:

	var msg = 'long'

	let message = `Hello world! ${msg}`; 
	console.log(message); // "Hello world!" 
	console.log(typeof message); // "string" 
	console.log(message.length); // 17
	
	// 反引号之内的所有空白符都是字符串的一部分,因此需要留意缩进。
	let message = `Multiline 
			string`; 
	console.log(message); 	// "Multiline 
							// 			string" 

	
	// 你可以轻易嵌入计算、函 数调用,等等
	let count = 10, price = 0.25, 
	message = `${count} items cost $${(count * price).toFixed(2)}.`; 
	console.log(message); // "10 items cost $2.50."

总结

以上的内容是通过阅读深入理解ES6摘出来的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静的小白菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值