侧边栏壁纸
  • 累计撰写 197 篇文章
  • 累计收到 496 条评论

JavaScript提取字符串的几种方式

2019-11-26 / 0 评论 / 36 阅读

第一种:

str = `"bar" and "foo" and "baz"`;
reg = /\"(.*?)\"/g
// 第一种方式
while (true) {
    let a = reg.exec(str)
    if (a === null) break;
    console.log(a[1])
}
// 成功提取
// index.js:7 bar
// index.js:7 foo
// index.js:7 baz
第二种:

// 第二种方式
console.log(str.match(reg))
// (3) [""bar"", ""foo"", ""baz""]
// 第二种方式有点小遐思 会多双引号
第三种:

// 第三种方式 利用replace
str.replace(reg, function(all, first) {
    console.log(first)
})
// 完美的成功输出了
第四种:

// 第三种方式
for (const i of str.matchAll(reg)) {
    console.log(i)
}
/*
(2) [""bar"", "bar", index: 0, input: ""bar" and "foo" and "baz"", groups: undefined]
(2) [""foo"", "foo", index: 10, input: ""bar" and "foo" and "baz"", groups: undefined]
(2) [""baz"", "baz", index: 20, input: ""bar" and "foo" and "baz"", groups: undefined]
*/
本章要点:

第三种方式是利用replace的高阶用法。replace的第二个参数不仅仅是可以传入需要替换的字符串,还可以传入一个函数,函数的第一个参数是所有匹配,第二个参数是捕获字符串

第四种方式显得更加简单利用matchAll生成可迭代对象然后进行遍历

评论一下?

OωO
取消