Javascript正则表达式:如何将一个变量放在正则表达式中?(Javascript Regex: How to put a variable inside a regular expression?)
所以例如:
function(input){ var testVar = input; string = ... string.replace(/ReGeX + testVar + ReGeX/, "replacement") }但这当然不工作:)有没有办法做到这一点?
So for example:
function(input){ var testVar = input; string = ... string.replace(/ReGeX + testVar + ReGeX/, "replacement") }But this is of course not working :) Is there any way to do this?
最满意答案
var regex = new RegExp("ReGeX" + testVar + "ReGeX"); ... string.replace(regex, "replacement");更新
根据一些注释,重要的是要注意,如果有潜在的恶意内容(例如变量来自用户输入),则可能需要转义该变量。
var regex = new RegExp("ReGeX" + testVar + "ReGeX"); ... string.replace(regex, "replacement");Update
Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)
Javascript正则表达式:如何将一个变量放在正则表达式中?(Javascript Regex: How to put a variable inside a regular expression?)所以例如:
function(input){ var testVar = input; string = ... string.replace(/ReGeX + testVar + ReGeX/, "replacement") }但这当然不工作:)有没有办法做到这一点?
So for example:
function(input){ var testVar = input; string = ... string.replace(/ReGeX + testVar + ReGeX/, "replacement") }But this is of course not working :) Is there any way to do this?
最满意答案
var regex = new RegExp("ReGeX" + testVar + "ReGeX"); ... string.replace(regex, "replacement");更新
根据一些注释,重要的是要注意,如果有潜在的恶意内容(例如变量来自用户输入),则可能需要转义该变量。
var regex = new RegExp("ReGeX" + testVar + "ReGeX"); ... string.replace(regex, "replacement");Update
Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)
发布评论