简体   繁体   中英

How to substitute a variable in a regex

I have a function that pulls out special modifiers from a string passed to a function

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;
}

What I'm not sure how to do (in this case), is how to abstract it so I can parse out an arbitrary leading character in the form of something like:

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

Is this possible?

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

Using the RegExp constructor allows you to use any variable, since it takes a string as input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM