ES6 ---- 字符串

  • 字符的unicode表示方法
A    "\u{41}"
B    "\u{42}"
C    "\u{43}"
hello   hell\u{6f}
  • codePointAt()
    JavaScript内部,字符以UTF-16的格式存储,每个字符固定占用2个字节,Unicode码大于0xFFFF的字符,占用两个字符

var s = "𠮷";
s.length // 2
s.charAt(0) // ''
s.charAt(1) // ''
s.charCodeAt(0) // 55362
s.charCodeAt(1) // 57271

codePointAt会正确的返回32位UTF-16字符的码点,对于正常单个的字符,返回结果与charCodeAt相同

var s = '𠮷a';
s.codePointAt(0) // 134071 返回'吉'
s.codePointAt(1) // 57271 返回的是'吉'的后两个字节
s.codePointAt(2) // 97 返回'a'
//转换成十六进制的值
s.codePointAt(0).toString(16) // "20bb7"
s.codePointAt(2).toString(16) // "61"


* 使用for of 循环可以正确识别32位的utf-16 字符

var s = '𠮷a';
for (let ch of s) {
console.log(ch.codePointAt(0).toString(16));
}
// 20bb7
// 61


* String.fromCodePoint()
String.fromCharCode()不能识别大于oxFFFF的码点
ES6提供的String.fromCharCode方法可以

String.fromCodePoint(0x20BB7)
// "𠮷"
String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y' //会把多个参数合成一个字符串返回
// true

* 字符串的遍历

for(let c of 'foo'){
conole.log(c);
}
// "f" "o" "o"

* 返回第一个字符

'abc'.at(0) // "a"
'𠮷'.at(0) // "𠮷"


* includes(), startsWith(), endsWith()

var s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
//这三个方法都支持第二个参数,从此位置开始
var s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false


* repeat()

'a'.repeat(3) //"aaa"
'a'.repeat(2.9) //"aa" 会进行取整
'a'.repeat(-0.9) //""
'a'.repeat(-1) //error 取整后值小于0会报错

* 模板字符串

var name= 'wang' ,age=18
my name is ${name},my age is ${age}
//my name is wang ,my age is 18

//模板字符换中所有的空格和换行都会保留在输出中
$('#list').html(<ul> <li>first</li> <li>second</li> </ul>);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容