034 js常用字符串方法
- length:获取字符串的长度。 例如:
"hello".length; // 输出 5
- charAt(index):返回指定索引处的字符。 例如:
"hello".charAt(1); // 输出 "e"
- concat(str):连接两个字符串并返回新的字符串。 例如:
"hello".concat(" world"); // 输出 "hello world"
- indexOf(substr, [start]):从一个字符串中搜索指定子串,并返回第一个匹配项的索引;如果未找到,则返回-1。 例如:
"hello world".indexOf("world"); // 输出 6
- lastIndexOf(substr, [start]):从一个字符串中反向搜索指定子串,并返回最后一个匹配项的索引;如果未找到,则返回-1。 例如:
"hello world world".lastIndexOf("world"); // 输出 12
- slice(start, [end]):截取一个字符串的一部分,并返回新的字符串。参数为起始索引(包含)和结束索引(不包含)。 例如:
"hello world".slice(0, 5); // 输出 "hello"
- substring(start, [end]):截取一个字符串的一部分,并返回新的字符串。参数为起始索引(包含)和结束索引(不包含),自动调整较小值作为起始索引。 例如:
"hello world".substring(0, 5); // 输出 "hello"
- substr(start, [length]):截取一个字符串的一部分,并返回新的字符串。参数为起始索引(包含)和指定长度。 例如:
"hello world".substr(0, 5); // 输出 "hello"
- replace(regexp/substr, newSubstr/function):替换字符串中匹配的子串或正则表达式,返回新的字符串。 例如:
"hello world".replace("world", "GPT-4"); // 输出 "hello GPT-4"
- toLowerCase():将字符串转换为小写字母形式,并返回结果。 例如:
"Hello World".toLowerCase(); // 输出 "hello world"
- toUpperCase():将字符串转换为大写字母形式,并返回结果。 例如:
"Hello World".toUpperCase(); // 输出 "HELLO WORLD"
- trim():去除字符串两端的空白字符,并返回结果。 例如:
" hello world ".trim(); // 输出 "hello world"