1、字符串的扩展
-
Unicode - \u0000 ~ \uFFFF
'\{u0061}' // a '\uD842\uDfB7' "\u{20BB7}" // "????"
-
字符串遍历器 - 识别大于 0xFFFF
let text2 = String.fromCodePoint(0x20BB7); for(let i = 0;i < text2.length;i++){console.log(text2[i]); } // � // � for (let i of text){console.log(i); } // "????"
-
模板字符串 - 保留所有空格与换行
const getName = () => 'Iven'; const myName = 'Eric'; `\`Hello\` ${getName()},I am ${myName}` //"`Hello` Iven,I am Eric"
-
标签模板
alert`111`; // alert(111); func`This ${a + b} is ${a * b}`; // func(['This', 'is', ''],a + b, a * b); <div> <span>1111</span> </div>
-
新增方法
-
fromCodePoint
– 从 Unicode 码点返回对应字符String.fromCodePoint(0x78, 0x1f680, 0x79); // x????y
-
String.raw
– 返回一个包括在内的字符串String.raw`\`Hello\` I am`; // \`Hello\` I am `\`Hello\` I am` // `Hello` I am String.raw({raw: 'test'}, 1,2,3,4); String.raw({raw: ['t','e','s','t']}, 1,2,3,4); // t1e2s3t
-
codePointAt
– 返回一个字符的码点(10 进制)let s = '????a'; s.codePointAt(0).toString(16); s.codePointAt(2).toString(16); // 61
-
includes
– 是否包含参数字符串const string = 'Hello world!'; string.includes('wo'); // true
-
startsWith
– 是否以某一个字符串开头const string = 'Hello world'; string.includes('He'); // true
-
endsWith
– 是否以某一个字符串结尾const string = 'Hello world'; string.includes('world'); // true
-
repeat
– 将原字符串重复 n 次`Hello`.repeat(2.9); // HelloHello `Hello`.repeat(-0.9); // ""
-
padStart
– 字符串补全长度`hello`.padStart(10,'0123456789'); // 01234hello
-
padEnd
`hello`.padEnd(10,'0123456789'); // hello01234
-
trimStart、trimEnd
– 去除空格,换行,tab'abc'.trimStart(); // abc
-
matchAll
– 返回正则表达式所有匹配for(s of 'abcabcabc'.matchAll('ab')) {console.log(s) }
-
2、正则的扩展
-
RegExp
– 指定修饰符new RegExp(/abc/ig,'i'); // /abc/i
-
字符串正则
– 内部改为调用 RegExp 方法RegExp.prototype[Symbol.match]; RegExp.prototype[Symbol.replace]; RegExp.prototype[Symbol.search]; RegExp.prototype[Symbol.split];
-
y 修饰符
– 全局粘连匹配const s = 'abcdabcdabc'; const reg1 = new RegExp('abc', 'g'); const reg2 = new RegExp('abc', 'y'); reg1.exec(s); reg2.exec(s)
-
sticky
– 是否使用了 y 修饰符const reg = /hello\d/y; reg.sticky; // true
-
flags
– 返回正则表达式的修饰符/abc/ig.flags // gi
-
s
– 匹配一切字符 (. 不能匹配回车、换行等行终止符)/week.month/s.test('week\nbar'); // false
-
组别名
(当我们使用正则匹配时,可以把它赋给一个变量)// 共同定义 const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/; const matchObj = RE_DATE.exec('1999-12-31'); const year = matchObj.groups.year; matchObj[1]; // 1999 const month = matchObj.groups.month; matchObj[2]; // 12 const day = matchObj.groups.day; matchObj[3]; // 31 let {groups: { one, two} } = /^(?<one>.*):(?<two>.*)$/u.exec('week:month');
-
matchAll
– 返回正则表达式所有匹配 – 迭代器for(s of 'abcabcabc'.matchAll('ab')) {console.log(s) }