String对象方法(二)at/charAt/charCodeAt/codePointAt/fromCodePoint/fromCharCode

523 阅读1分钟

String对象方法at/charAt/charCodeAt/codePointAt/fromCodePoint/fromCharCode

at:获取对应索引位置的字符。传入负数表示从数组尾部计数

let str = "hello world";
console.log(str.at(1), str.at(7), str.at(-2));
//e o l

charAt:获取对应索引位置的字符。传入负数则返回空字符串

let str = "abcdefg";
console.log(str.charAt(0), str.charAt(3)); // a d
console.log(str.charAt(-2)); // 空字符串

charCodeAt:获取对应索引位置字符的ASCII码。传入负数则返回NaN

let str = "abcdefg";
console.log(str.charCodeAt(0), str.charCodeAt(3)); // 97 100
console.log(str.charCodeAt(-2)); // NaN

codePointAt:获取对应索引位置字符的Unicode编码。传入负数则返回undefined

let str = "abcdefg";
console.log(str.codePointAt(0), str.codePointAt(3)); // 97 100
str = '\uD800\uDC00';
console.log(str.codePointAt(0)); // 65536
console.log(str.codePointAt(-1)); // undefined

fromCodePoint:通过ASCII码构造字符串

console.log(String.fromCharCode(97, 100, 190, 61));
//ad¾=

fromCharCode:通过Unicode编码构造字符串

console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
//☃★♲你