length属性:表示字符串包含多少16位码元
charAt():方法返回给定索引位置的字符
charCodeAt() :可以查看指定码元的字符编码
String.fromCharCode():这个方法可以接受任意多个数值,返回字符串
console.log(String.fromCharCode(0x61, 0x62, 0x63, 0x64, 0x65)); // "abcde"
codePointAt():正确解析既包含单码元字符又包含代理对字符的字符串(如笑脸)
let message = "ab?de";
console.log(message.codePointAt(2)); //128522
String.fromCodePoint():类似fromCharCode() 接收码点
某些Unicode字符可以有多种编码方式
normalize():接收一个标准 "NFD"、"NFC"、"NFKD"或"NFKC" 对字符进行统一标准化,以方便比较
console.log(a1 === a1.normalize("NFD")); // false
字符串原型暴露了[Symbol.iterator] () ,用来迭代每个字符
let message = "abc";
let stringIterator = message[Symbol.iterator]();
console.log(stringIterator.next());
//{value: "a", done: false}
console.log(stringIterator.next());
//{value: "b", done: false}
console.log(stringIterator.next());
//{value: "c", done: false}
console.log(stringIterator.next());
//{value: undefined, done: true}
可以通过for-of循环访问每个字符:
for (const c of "abcde") {
console.log(c);
}
// a
// b
// c
// d
// e
解构操作
let message = "abcde";
console.log([...message]); // ["a", "b", "c", "d", "e"]
注:可以把(...)解构操作符 理解为迭代结果用逗号分隔,所以
...message 可以看成 "a", "b", "c", "d", "e" ,再加方括号 即为结果。
toLowerCase()、toLocaleLowerCase()、 toUpperCase()和toLocaleUpperCase() 这两个用于特定地区语言
本质与RegExp的exec() 方法相同。方法接收一个参数:正则表达式对象,或表达式字符串
let text = "cat,bat";
let pattern = /(.)at/i;
let matches = text.match(pattern)
//let matches = pattern.exec(text); 等价
//["cat", "c", index: 0, input: "cat,bat", groups: undefined]
console.log(matches[0]); // "cat"
console.log(matches[1]); // "c"
console.log(matches.lastIndex); //没有使用全局匹配,永远为0
查找模式,方法接收一个参数:正则表达式对象,或表达式字符串。返回模式第一个匹配的位置索引,如果没找到则返回-1。
let text = "cat, bat, sat, fat";
let pos = text.search(/at/);
console.log(pos); // 1
用于替换字符串,方法接收两个参数,第一个参数为RegExp对象或字符串、第二个参数为字符串或函数。
第一个参数为字符串则只会替换第一个字符串,如果全部替换,正则表达式必须带全局标记。
第二个参数是字符串时有几个特殊字符,可用来表示匹配到的值
$n:n为0-9,$1表示第一个捕获组的字符串
let text = "bat, cat, fat, tat";
let pattern = /(.)at/g;
let result = text.replace(pattern,"$1$1"); //$1表示分组1 也就是at前面的字符
console.log(result); //"bb, cc, ff, tt"
第二个参数是函数,函数会接收三个参数:匹配的整个字符串、匹配索引、整个字符串。(多个捕获组会传多次)。
函数应该返回一个字符串,表示替换内容。
function htmlEscape(text) {
return text.replace(/[<>"&]/g,
function(match, pos, originalText) {
switch(match) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "\"":
return """;
}
});
}
console.log(htmlEscape("<p class=\"greeting\">Hello world!</p>"));
// "<p class="greeting">Hello world!</p>"
用于将字符串分割为数组,第一个参数可以是RegExp对象或字符串,第二个可选参数用于指定数组最大大小。
let colorText = "red,blue,green,yellow";
let colors1 = colorText.split(",");
// ["red", "blue", "green", "yellow"]
let colors2 = colorText.split(",", 2);
// ["red", "blue"]
let colors3 = colorText.split(/[^,]+/);
// ["", ",", ",", ",", ""] 如果分隔符在开头和结尾出现,数组的前后就会出现空字符串元素
localeCompare() 按照字母表原字符串应该排在字符串参数前头,则返回负值,相等为0,排在后面则为正值。
let stringValue = "yellow";console.log(stringValue.localeCompare("brick")); // 1
此方法支持多国语言
原文:https://www.cnblogs.com/ku1a/p/14766660.html