如何在正则表达式中替换变量
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 构造函数允许您使用任何变量,因为它将字符串作为输入。
相关文章:
- window.location替换并传递URL历史记录条目中的变量
- 替换变量时,JavaScript字符串replace()不起作用
- 在 Javascript 中替换变量的值
- JavaScript正则表达式替换变量
- 如何替换变量中的更多字符串
- 替换变量[Javascript]时出现问题
- "[对象对象]”;在警报提示中使用时替换变量字符串
- 通过jQuery替换变量和静态文本
- Swap()函数用于替换变量'
- 用函数(变量)替换变量
- 数据表用其作用域之外的数据替换变量
- Javascript替换变量"在HTML代码中更快
- 在TinyMCE中保存替换变量,但在可视化编辑器中显示替换的内容
- 替换变量中的字符
- 用gulp替换变量
- Javascript正则表达式:替换变量
- 如何使用jquery替换变量中的元素并在另一个变量中获取结果
- 用grunt替换变量
- 如何在正则表达式中替换变量
- 如何替换变量设置的 Replace() - Javascript