正则表达式能实现Template strings的功能吗?
发布于 8 年前 作者 jiangliqin 3468 次浏览 来自 问答
  1. 我先描述下我的问题: 我格式化当前标准格式日期:2016-03-26 ,我写了一个匹配时间的正则表达式,/\d{4}-\d{2}-[\d{2}(-\d{2})*] /,然后匹配2016-03-[26-28]这个字符串。

2.提问 我想把当前时间的D天,动态替换正则表达式中表示天的那部分\d{2},在正则中不能用类似于es6 中Template strings 的${}的部分替换,请教大侠们该怎么做,写成这种动态的正则表达式

4 回复

用()捕获,然后可以替换

比如 (\d{4})(\d{2})匹配成了后 $1 代表第一个4个数字 $2代表 两个数字 你要留下一 替换表达式就可以写成 $1xxxx

@luicfer 我没啥文化,看不懂,你能举个例子吗?

这样吗?

'use strict';

// input ${year}-${month}-${day}
// output 2016-03-27

const year = '2016';
const month = '03';
const day = '27';

/**
 * render
 *
 * @name render
 * @function
 * @access public
 * @param {String} template 需要渲染的字符串
 * @returns {String} 渲染完成后的字符串
 */
function render(template) {
  // 匹配所有 ${}
  const RE = /\$\{(.*?)\}/g;
  const res = template.replace(RE, (c) => {
    // 获取 ${st} 中的 st
    const st = /\$\{(.+?)\}/.exec(c)[1];
    // 暴力 eval ,获取表达式的值
    return eval(st);
  });
  return res;
}

// 调用示例
const str = render('${year}-${month}-${day}');

console.log('--------------->', str);

回到顶部