String
charAt()
用于返回指定位置(下标)的字符。
const str = 'helio guys';
console.log(str.charAt(3))// i
charCodeAt()
用于返回指定位置的字符的Unicode编码。
const str = 'helio guys';console.log(str.charCodeAt(3)); //105
match()
用于在字符串内检索指定的值或找到一个或多个正则表达式的匹配,返回的是值而不是值的位置。
const str = 'hello guys';
console.log(str.match('guys')) // ["guys"]
// 使用正则匹配字符串
const strs = '1.hello guys, 2.are you ok?';
console.log(strs.match(/\d+/g)) // ["1", "2"]
replace()
替换匹配的字符串。
const str = 'hello guys';
console.log(str.replace('guys', 'man')) // hello man
search()
用于检索与字符串匹配的子串,返回的是地址,与indexOf()
的区别是 search
是强制正则的,而 indexOf
只是按字符串匹配的。
const str = 'hello guys';
console.log(str.search('guys')) // 6
console.log(str.indexOf('guys')) // 6
// 区别
const string = 'abcdefg.1234';
console.log(string.search(/\./)) // 7(转译之后可以匹配到 . 的位置)
console.log(string.indexOf(/\./)) // -1 (相当于匹配/\./,找不到则返回-1,只能匹配字符串)
split()
将字符串切割成数组。
const str = 'hello guys';
console.log(str.split('')) // ["h", "e", "l", "l", "o", " ", "g", "u", "y", "s"]
console.log(str.split('', 3)) // ["h", "e", "l"]
toLocaleLowerCase()& toLowerCase()
将字符串转换成小写。
toLocaleUpperCase() & toUpperCase()
将字符串转换成大写。
substr()
用于从起始索引号提取字符串中指定数目的字符。
const str = 'hello guys';
console.log(str.substr(2)) // llo guys
console.log(str.substr(2, 7)) // llo gu
console.log(str1.substr(-3)) //uys
substring()
用于提取字符串中两个指定索引号之间的字符。(与 slice()
和 substr()
方法不同的是,substring()
不接受负的参数。)
.trim()
去掉字符串两端的空格。