javascript - 如何替换正则表达式中的变量

标签 javascript regex

我有一个函数,可以从传递给函数的字符串中提取特殊修饰符

function parseContext(record, txtInput) {
    var context = String((txtInput.match(/(^\@[\w\n]*)/g) || [""])[0]).replace("@", "");
    record.entry = txtInput;
    if (command && command.length) {
        txtInput = String(txtInput).replace("/" + command, "");
        record.command = command;
        record.entry = txtInput;
    }
    return record;
}

我不确定该怎么做(在这种情况下),是如何抽象它,以便我可以解析出类似以下形式的任意前导字符:

function parseModifier(record, modifier, txtInput) {
    var command = String((txtInput.match(/(^\  ---what goes here? --- [\w\n]*)/g) || [""])[0]).replace(modifier, "");

这可能吗?

最佳答案

var re = new RegExp('(^\\' + anyVariable + '[\w\n]*)', 'g');
var command = String((txtInput.match(re || [""])[0]).replace(modifier, "");

使用RegExp构造函数允许您使用任何变量,因为它接受字符串作为输入。

关于javascript - 如何替换正则表达式中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14632101/

相关文章:

javascript - Angular 插值无法正常工作?

javascript - Jquery InputMask 动态验证

javascript - 正则表达式忽略长度达到 10 后的数字

javascript - 正则表达式字符串显示错误

Javascript正则表达式以逗号分割行

javascript - PHP 无法上传图像,也看不到 $image 值。所有其他工作,都是关于ajax,没有刷新表单

JavaScript 获取网站 URL

javascript - html5 canvas在firefox下性能不佳

javascript - 如何在 VueJS 0.11 中将 bool 变量输出为 "yes/no"?

java - 有人可以检查这个正则表达式语句吗?