String对象方法(五)repeat/replace/replaceAll/search/slice/split

156 阅读1分钟

String对象方法repeat/replace/replaceAll/search/slice/split

repeat:复制指定数量的字符串

let str = 'abc';
console.log(str.repeat(5));
// abcabcabcabcabc

replace:对匹配到的第一个指定字符串替换为相应的字符串,可用正则进行匹配

let str = 'hello world hello';
console.log(str.replace("hello", "haha"));
// haha world hello
str = 'aaaabbbbaaaabbbb';
console.log(str.replace(/b{4}/g, "wwww"));
// aaaawwwwaaaawwww

replaceAll:对匹配到所有字符串替换为相应的字符串,可用正则进行匹配

let str = 'hello world hello';
console.log(str.replaceAll("hello", "haha"));
// haha world haha
str = 'aaaabbbbaaaabbbb';
console.log(str.replaceAll(/b{4}/g, "wwww"));
// aaaawwwwaaaawwww

search:根据字符串或正则表达式搜索结果

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const regex = /[^\w\s]/g;
console.log(paragraph.search(regex));
// 43
console.log(paragraph.search("brown"));
// 10

slice:切割字符串

let str = "hello world";
console.log(str.slice(0, 3));
// hel
console.log(str.slice(2, 5));
// llo

split:根据某个字符对字符串进行切割,同时可以限制切割的次数,并返回数组

let str = "hello world";
console.log(str.split(""));
// ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
console.log(str.split(" "));
// ['hello', 'world']
console.log(str.split("l", 2));
// ['he', '']