Skip to content

Commit 0ded650

Browse files
committed
修改sting/u-modifier
1 parent dc6437d commit 0ded650

File tree

1 file changed

+59
-17
lines changed

1 file changed

+59
-17
lines changed

docs/string.md

Lines changed: 59 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -41,21 +41,6 @@ codePointAt方法是测试一个字符由两个字节还是由四个字节组成
4141

4242
```javascript
4343

44-
function is32Bit(c) {
45-
return c.codePointAt(0) > 0xFFFF;
46-
}
47-
48-
is32Bit("𠮷") // true
49-
is32Bit("a") // false
50-
51-
```
52-
53-
## String.fromCodePoint方法
54-
55-
该方法用于从Unicode编号返回对应的字符串,作用与codePointAt正好相反。
56-
57-
```javascript
58-
5944
String.fromCodePoint(134071) // "𠮷"
6045

6146
```
@@ -100,9 +85,13 @@ ES6对这一点做出了改进,只要将超过0xFFFF的编号放入大括号
10085

10186
ES6对正则表达式添加了u修饰符,用来正确处理大于\uFFFF的Unicode字符。
10287

88+
**(1)点字符**
89+
90+
点(.)字符在正则表达式中,解释为除了换行以外的任意单个字符。对于大于\uFFFF的Unicode字符,点字符不能识别,必须加上u修饰符。
91+
10392
```javascript
10493

105-
var s = "𠮷";
94+
大于\uFFFF的Unicode字符var s = "𠮷";
10695

10796
/^.$/.test(s) // false
10897
/^.$/u.test(s) // true
@@ -111,6 +100,46 @@ var s = "𠮷";
111100

112101
上面代码表示,如果不添加u修饰符,正则表达式就会认为字符串为两个字符,从而匹配失败。
113102

103+
**(2)Unicode字符表示法**
104+
105+
ES6新增了使用大括号表示Unicode字符,这种表示法在正则表达式中必须加上u修饰符,才能识别。
106+
107+
```javascript
108+
109+
/\u{61}/.test('a') // false
110+
/\u{61}/u.test('a') // true
111+
/\u{20BB7}/u.test('𠮷') // true
112+
113+
```
114+
115+
上面代码表示,如果不加u修饰符,正则表达式无法识别\u{61}这种表示法,只会认为这匹配属61个连续的u。
116+
117+
**(3)量词**
118+
119+
使用u修饰符后,所有量词都会正确识别大于\uFFFF的Unicode字符。
120+
121+
```javascript
122+
123+
/a{2}/.test('aa') // true
124+
/a{2}/u.test('aa') // true
125+
/𠮷{2}/.test('𠮷𠮷') // false
126+
/𠮷{2}/u.test('𠮷𠮷') // true
127+
128+
```
129+
130+
**(4)预定义模式**
131+
132+
u修饰符也影响到预定义模式,正确识别大于\uFFFF的Unicode字符。
133+
134+
```javascript
135+
136+
/^\S$/.test('𠮷') // false
137+
/^\S$/u.test('𠮷')
138+
139+
```
140+
141+
上面代码的`\S`是预定义模式,匹配所有不是空格的字符。只有加了u修饰符,它才能正确匹配大于\uFFFF的Unicode字符。
142+
114143
利用这一点,可以写出一个正确返回字符串长度的函数。
115144

116145
```javascript
@@ -127,6 +156,19 @@ codePointLength(s) // 2
127156

128157
```
129158

159+
**(5)i修饰符**
160+
161+
有些Unicode字符的编码不同,但是字型很相近,比如,\u004B与\u212A都是大写的K。
162+
163+
```javascript
164+
165+
/[a-z]/i.test('\u212A') // false
166+
/[a-z]/iu.test('\u212A') // true
167+
168+
```
169+
170+
上面代码中,不加u修饰符,就无法识别非正规的K字符。
171+
130172
## contains(), startsWith(), endsWith()
131173

132174
传统上,JavaScript只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。ES6又提供了三种新方法。
@@ -251,7 +293,7 @@ console.log(`${ x } + ${ y } = ${ x + y}`)
251293
上面代码表示,在模板字符串中嵌入变量,需要将变量名写在${}之中。
252294

253295
模板字符串使得字符串与变量的结合,变得容易。下面是一个例子。
254-
296+
This article explains the effects of the u flag. It helps if you’ve read JavaScript has a Unicode problem first.
255297
```javascript
256298

257299
if (x > MAX) {

0 commit comments

Comments
 (0)