簡體   English   中英

如何在正則表達式中替換變量

[英]How to substitute a variable in a 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構造函數使您可以使用任何變量,因為它將字符串作為輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM