如题,想给代码做个高亮,现在有这么个需求
比如现在有 html 字符串如下:
2020-01-01 20:20:20 [INFO] log test 1
2020-02-02 10:10:10 [INFO] log test 2
我想讲这个字符串修改为这样
2020-01-01 20:20:20 [INFO] log test 1
2020-02-02 10:10:10 [INFO] log test 2
即用正则表达式匹配到时间,然后再将匹配到的字符串两边加上
,
正则的部分很简单可以匹配到,但是替换怎么搞呢?
有没有 js 大佬讲解一下这个需求能不能通过string.replace(/regexp/g , 'target')
这种命令来完成,还是说要写一大段搜索-替换的逻辑才行
string.replace(/regexp/g , '
$&')
时间的匹配你自己修改一下
"2020-01-01 [INFO] log test 1".replace(/(\d{4}-\d{2}-\d{2})/g, '
$1')
$1 表示正则中,第一个括号括起来的内容
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
'2020-01-01 20:20:20 [INFO] log test 1'.replace(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})(.*)$/, (match, p1, p2) => `
${p1}${p2}`)
replace 参数 2 支持匿名函数,写 /看 起来比较清晰点
let str='2020-01-01 20:20:20 [INFO] log test 1\n2020-02-02 10:10:10 [INFO] log test 2';
str.replace(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/g,'
$&');