字符串的常见方法包括操作方法,转换方法,匹配方法
1.操作方法
-
concat用于将一个或多个字符串拼接成一个新字符串
let string1 = "hello"
let string2 = string1.concat("world")
console.log(string2) // "helloworld"
console.log(string1) // "hello"
除了上述方法之外,还可以使用+或者模板字符串使用${}进行拼接
let string1 = "hello"
string1 = string1 + "world"
console.log(string1) // "helloworld"
let string2 = "world"
let result = `${string1}${string2}`
console.log(result) // "helloworld"
slice() 、 substr() 、 substring()三个方法都是返回调用它们的字符串的一个子字符串,
上述三个方法类似,需要注意的是substr()第二个参数是需要提取的长度
let stringValue = "hello world";
console.log(stringValue.slice(3)); // "lo world"
console.log(stringValue.substring(3)); // "lo world"
console.log(stringValue.substr(3)); // "lo world"
console.log(stringValue.slice(3, 7)); // "lo w"
console.log(stringValue.substring(3,7)); // "lo w"
console.log(stringValue.substr(3, 7)); // "lo worl"
第二个参数都可以省略,省略则默认读到末尾,对于slice()而言,要是传入的为负数,则视为从字符串末尾开始的位置,例如slice(-3)则从字符串的倒数第三个字符串开始提取
substring()方法类似slice(),但两个参数中任意一个为负数都会被视为0,若第一个参数比第二个大则会交换位置;以及第二个参数大于等于字符串长度时,会被视作为字符串末尾。
let stringValue = "na";
let copyResult = stringValue.repeat(2) // nana
trim(),trimLeft(),trimRight()删除前,后或前后所有空格符,然后返回新的字符串
let stringValue = " hello world ";
let trimmedStringValue = stringValue.trim();
console.log(stringValue); // " hello world "
console.log(trimmedStringValue); // "hello world"
repeat()接收一个整数参数,表示要将字符串复习多少次,然后返回复制后的结果
toLowerCase(),toUpperCase()大小写转化
let stringValue = "hello world";
console.log(stringValue.toUpperCase()); // "HELLO WORLD"
console.log(stringValue.toLowerCase()); // "hello world"
charAt()返回给定索引位置的字符,要是给定索引位置超出范围,则返回一个空字符串
let message = "abcde";
console.log(message.charAt(2)); // "c"
indexOf()第一个参数从字符串开头搜索传入的字符串,返回第一个匹配的位置,第二个参数(可选)表示开始搜索的位置
let str = "Hello world";
console.log(str.indexOf("l", 3)); // 输出: 9
startWith()从字符串中开头搜索传入的字符串,判断是否以传入的字符串开头,是返回true,否则false
include()从字符串中开头搜索传入的字符串,只要字符串中包含传入的字符串,则返回true,否则false
let message = "foobarbaz";
console.log(message.startsWith("foo")); // true
console.log(message.startsWith("bar")); // false
console.log(message.includes("bar")); // true
console.log(message.includes("qux")); // false
2.转换方法
split()将字符串按照指定的分割符拆分成数组的每一项,返回该数组
let str = '1+2+3+4'
let arr = str.split('+')
console.log(arr) // ['1','2','3','4']
let arr1 = str.split('+').map(Number)//直接传递一个函数的名称,会作为回调函数执行
//上述等效于map(item=>Number(item))
console.log(arr1) //[1,2,3,4]
3.模板匹配方法
match()接收一个参数,可以是正则表达式字符串,也可以是一个RegExp对象(通过RegExp构造函数构造一个RegExp对象,eg:let regex = new RegExp('pattern'); // pattern 是要匹配的正则表达式)
let text = "cat, bat, sat, fat";
let pattern = /.at/;
let matches = text.match(pattern);
console.log(matches[0]); // "cat"
若是上述中pattern改为'/.at/g'则会全局匹配,matches会变为['cat', 'bat', 'sat', 'fat']
search()接收一个参数,可以是正则表达式字符串,也可以是一个RegExp对象,找到则返回第一个匹配索引,否则返回-1
replace()接收两个参数,第一个为匹配内容,第二个为要替换的元素,需要注意的是,只会替换第一个匹配的元素
let text = "cat, bat, sat, fat";
let result = text.replace("at", "ond");
console.log(result); // "cond, bat, sat, fat"
若是要全局替换,可以将"at"改为"at/g"或者使用replaceAll()

被折叠的 条评论
为什么被折叠?



