字符串扩展

xiaoxiao2021-02-28  60

字符串扩展

codePointAt()

codePoint对于中文字符的当前位置取到的就是当前中文字,对于后一位取到的是中文字符内的第二个字符,如果想一个一个区分每个字需要用for….of….

let s = '��a'; s.codePointAt(0) // 13407---�� s.codePointAt(1) // 57271---��的第二个字符 s.codePointAt(2) // 97---a

String.fromCodePoint()

相较es5提供的String.formCharCode方法,可以识别大于0xFFFF的码点

String.fromCodePoint(0x20BB7) // "��" String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y' // true

字符串的遍历器接口

es6添加了字符串的遍历接口,字符串可以被for…of遍历且可以识别中文字符

for (let codePoint of 'foo') { console.log(codePoint) } // "f" // "o" // "o"

at()

相较于charAt可以获取整个中文字符

'abc'.charAt(0) // "a" '��'.charAt(0) // "\uD842" 'abc'.at(0) // "a" '��'.at(0) // "��"

includes(),startsWith(),endsWith()

相较于原来的方法 ,可以有第二个参数来设置开始搜索的位置

let s = 'Hello world!'; s.startsWith('Hello') // true s.endsWith('!') // true s.includes('o') // true s.startsWith('world', 6) // true s.endsWith('Hello', 5) // true s.includes('Hello', 6) // false

repeat()

返回一个新字符串,表示原字符串重复n次

'x'.repeat(3) // "xxx" 'hello'.repeat(2) // "hellohello" 'na'.repeat(0) // ""

padStart() ,padEnd()

用于补全长度,当长度不满足时,用于补全

'x'.repeat(3) // "xxx" 'hello'.repeat(2) // "hellohello" 'na'.repeat(0) // ""

模板字符串

多行字符串可以直接顶意思 ,且可以在字符串中直接嵌入变量

// 普通字符串 `In JavaScript '\n' is a line-feed.` // 多行字符串 `In JavaScript this is not legal.` console.log(`string text line 1 string text line 2`); // 字符串中嵌入变量 let name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?`

模板会保存所有空格和换行 如果不需要可以用trim

$('#list').html(` <ul> <li>first</li> <li>second</li> </ul> `.trim());

${}里可以放任意变量,函数,表达式

标签模板

字符串模板紧跟在函数名后面,字符串模板会作为参数直接执行

alert`123` // 等同于 alert(123)

如果字符串模板内含有参数,会先处理成多个参数,再调用函数

let a = 5; let b = 10; tag`Hello ${ a + b } world ${ a * b }`; // 等同于 tag(['Hello ', ' world ', ''], 15, 50);

通过方法将参数放入原来的位置

let msg = passthru`The total is ${total} (${total*1.05} with tax)`; function passthru(literals, ...values) { let output = ""; let index; for (index = 0; index < values.length; index++) { output += literals[index] + values[index]; } output += literals[index] return output; }

字符串输出,存在一个raw方法

console.log`123` // ["123", raw: Array[1]]

raw的数组里的字符串会吧字符串的内的符号转义

tag`First line\nSecond line` function tag(strings) { console.log(strings.raw[0]); // strings.raw[0] 为 "First line\\nSecond line" // 打印输出 "First line\nSecond line" }

String.raw()

讲字符串转义

String.raw`Hi\n${2+3}!`; // 返回 "Hi\\n5!" String.raw`Hi\u000A!`; // 返回 "Hi\\u000A!"

raw方法作为一个函数使用

String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t' // 等同于 String.raw({ raw: ['t','e','s','t'] }, 0, 1, 2);
转载请注明原文地址: https://www.6miu.com/read-2625379.html

最新回复(0)