JS - 使用正则表达式获取字符串里的部分内容(截取两个字符串之间内容

作者: hangge 发布时间: 2019-09-02 浏览: 3254 次 编辑

(1)有时我们需要从一个字符串中提取出需要的部分,这个借助正则表达式就可以很方便地实现。比如:从下面的字符串中根据 key(冒号前面部分)获取对应的 value(冒号后面的部分)

1
time:2019,status:open,count:3


(2)为方便使用我们封装一个方法:

1
2
3
4
5
6
// 从字符串中根据key获取对应的value值
// 字符串格式:key1:value1,key2:value2,........
function getValue(str, key){
  let result = new RegExp(`(?:^|,)${key}:([^,]*)`).exec(str);
  return result && result[1]
}


(3)使用样例如下:

1
2
3
4
var str = "time:2019,status:open,count:3";
console.log("time:", getValue(str, 'time'));
console.log("status:", getValue(str, 'status'));
console.log("count:", getValue(str, 'count'));

原文:JS - 使用正则表达式获取字符串里的部分内容(截取两个字符串之间内容)


原文链接:https://www.hangge.com/blog/cache/detail_2501.html