Javascript 如何替换正则表达式中的变量
我有一个函数,它从传递给函数的字符串中提取特殊的修饰符Javascript 如何替换正则表达式中的变量,javascript,regex,Javascript,Regex,我有一个函数,它从传递给函数的字符串中提取特殊的修饰符 function parseContext(record, txtInput) { var context = String((txtInput.match(/(^\@[\w\n]*)/g) || [""])[0]).replace("@", ""); record.entry = txtInput; if (command && command.length) { txtInput
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, "");
使用构造函数可以使用任何变量,因为它接受字符串作为输入
使用构造函数可以使用任何变量,因为它接受字符串作为输入。谢谢!在第二行添加了结尾部分(我相信编辑待定)我的编辑不正确,应该是:new RegExp(“(^\\”+modChar+“[\\w\\n]*),“g”),谢谢!在第二行添加了一个结束参数(我相信编辑待定)我的编辑不正确,应该是:new RegExp(“(^\\”+modChar+“[\\w\\n]*),“g”),