Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:有没有一种方法可以在正则表达式中使用变量来搜索什么?_Javascript_Regex - Fatal编程技术网

Javascript:有没有一种方法可以在正则表达式中使用变量来搜索什么?

Javascript:有没有一种方法可以在正则表达式中使用变量来搜索什么?,javascript,regex,Javascript,Regex,我使用slice()方法测试变量的内容是否在主字符串中 我想用正则表达式。但是,我不知道如何将变量放入正则表达式中 以下是我所做的: function verifySubstrs(mainStr, head, body, tail) { // Verify if the 1st string starts with the 2nd string, var headLength = head.length; if(mainStr.slice(0, headLe

我使用slice()方法测试变量的内容是否在主字符串中

我想用正则表达式。但是,我不知道如何将变量放入正则表达式中

以下是我所做的:

    function verifySubstrs(mainStr, head, body, tail) {

    // Verify if the 1st string starts with the 2nd string, 
    var headLength = head.length;

    if(mainStr.slice(0, headLength) !== head){
        return "Incomplete.";
    }
这是我想做的。 我想使用变量“head”,其中包含文本“head”

如果我可以在搜索的内容中使用一个变量,我可以使用相同的技术来查找主体内的身体和末端的尾巴。
我正在寻找技术,而不仅仅是这个特定项目的解决方案。

您可以从字符串编译regexp。试试这个:

var regexp = new RegExp("^" + head);
var TF = regexp.test(mainStr);

注意:您可以这样做:
if(mainStr.indexOf(head)==0)
。为什么不使用第一种方法呢?它比创建一个动态正则表达式要干净得多。(
mainStr.startsWith(head)
也适用于现代JavaScript。)谢谢,ibrahim mahrir。我补充了更多的细节。Ryan:我很想知道未来的编码是否可行。ibrahim mahrir:你能提供一个我重复的上一个问题的链接吗?当我输入问题时,没有相关的内容。(我意识到该页面上的搜索并不全面。)
var regexp = new RegExp("^" + head);
var TF = regexp.test(mainStr);