ES6 第二章 字符串与正则表达式
- 引言
书中这一章节的第一部分讲的是更好的Unicode支持,没看懂,就从字符串的其他改动开始自己的学习
2. ES6新增的字符串的相关方法
- includes() 方法,在给定文本存在于字符串中的任意位置时会返回true,否则返回false
-
startsWith() 方法,在给定文本出现在字符串起始位置时会返回true,否则返回false
-
endsWith() 方法,在给定文本出现在字符串结尾处时返回true,否则返回false
3. 上述三种方法如何使用
给出实例之前先给一个说明,上述三种方法都支持传俩个参数,最少只传一个参数,第一个参数是要进行匹配的字符串,第二个参数是匹配的起始位置,注意endsWith第二个参数的不同
var msg = "hello world!"
console.log(msg.startsWith("Hello")) //true
console.log(msg.startsWith("o",4)) //true
console.log(msg.endsWith("!")) //true
console.log(msg.endsWith("o",8)) //true 注意这个8是从倒数开始
console.log(msg.includes("o")) //true
console.log(msg.includes("o",8)) //false 从r的位置开始匹配
4. repeat()方法
//example1 简单使用
console.log("x".repeat(3)) //xxx
console.log("ab".repeat(4)) //ababab
//example2
var indent = " ".repeat(4),
indentLevel = 0
var newIndent = indent.repeat(++indentLevel)
5. 正则新增y标志
- 定义 :y标志影响正则表达式搜素时的粘连属性,它表示从正则表达式的lastIndex属性值的位置开始检索字符串中的匹配字符,如果在该位置没有匹配成功,那么正则表达式将停止检索
- 使用实例
var text = "hello1 hello2 hello3"
pattern = /hello\d\s?/,
result = pattern.exec(text)
globalPattern = /hello\d\s?/g,
globalResult = globalPattern.exec(text)
stickyPattern = /hello\d\s?/y
stickyResult = stickyPattern.exec(text)
console.log(result[0]) //只匹配到一个是"hello1 " index=0
console.log(globalResult[0]) //只匹配到一个是"hello1 " index=7
console.log(stickyResult[0]) //只匹配到一个是"hello1 "
//三个模式的lastIndex属性全部被更改为1,表示三个模式的正则表达式都应当从第二个字符开始尝试匹配
pattern.lastIndex = 1 //无影响
globalPattern.lastIndex = 1 //导致从第二个字符开始匹配
stickyPattern.lastIndex = 1 //粘连的字符串从lastIndex位置匹配,第一次匹配未成功就为null
result = pattern.exec(text)
globalResult = globalPattern.exec(text)
stickyResult = stickyPattern.exec(text)
console.log(result[0]) //只匹配到一个是"hello1 " index=0
console.log(globalResult[0]) //只匹配到一个是"hello2 " index=7
console.log(stickyResult) //null
- 属性 (粘连性)
var pattern = /hello\d/y
console.log(pattern.sticky) //true
//如果粘连标志存在,那么sticky属性的值会被设为true,否则会被设为false,sticky属性是由y标志决定,只读属性
//检测是否支持y
function hasRegExpy() {
try {
var pattern = new RegExp(".","y")
return true
} catch (ex) {
return false
}
}
- 正则表达式的复制
var re1 = /ab/i //i表示忽略大小写
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
- flags属性(正则使用)
//ES6之前对应的方法
function getFlags(re) {
var text = re.toString();
return text.substring(text.lastIndexOf("/")+1, text.length);
}
var re = /ab/g
getFlags(re) //g
//ES6新增
console.log(re.source)//ab
console.log(re.flags) //g
6. 引入模版字面
- 定义 使用反引号(`)来包裹普通字符串,而不是用双引号或单引号
- 使用实例
//example1
let name = "madongmei"
message = `hello, ${name}`
console.log(message) //"hello, madongmei"
//example2
let count = 10
price = 0.25
message = `${count] items cost $${(count * price).toFixed(2)}`
console.log(message) //10 items cost $2.50
//example3
let name = "madongmei"
message = `hello, ${
`my name is ${ name }`
}`
console.log(message) //hello, my name is madongmei