Creating a RegExp in JavaScript from user input My goal is to accept user input regex in the following forms

/regex|here/i
/regex|here/
regex|here

From there I want to be able to pass that to a function and return a RexExp object for use later with string.match()

I came up with the below to achieve that, and not break the caller which is expecting the RegExp object returned.  Is there any part of this that I'm doing wrong or exceedingly sub-optimally?  (I'm not very familiar with Javascript).

function regGen(uInput)
{
    var inReg = "";
    var inMod = "";
    var outReg = /(?!)/

    if(uInput[0] == "/" &amp;&amp; uInput[uInput.length-1] == "/")
    {
        inReg = uInput.slice(1,uInput.length-1);
    }
    else if(uInput[0] == "/")
    {
        var temp = uInput.split("/");
        inMod = temp[temp.length-1];
        inReg = temp; 
            inReg.pop(); 
            inReg.shift();
        inReg = inReg.join("/");
    }
    else
    {
        inReg = uInput;
    }
    try {
        outReg = new RegExp(inReg,inMod);
    }
    catch(err)
    {
        alert("Malformed Regex");
    }
    return outReg;
}
The else if block was pretty hard to follow.  I would say that your function has rather weird behaviour (treating the text as flags) if the input has a leading slash but no trailing slash.

Anyway, even if you are not very familiar with JavaScript, surely you are familiar with regular expressions?  Why not just use a regular expression to parse your regular expression?

function regGen(uInput) {
    var regExpParser = new RegExp("^/(.*)/(.*)|(.*)");
    var match = uInput.match(regExpParser);
    return new RegExp(match[1] || match[3], match[2]);
}


Strictly speaking, we should both be more careful about interpreting possible backslashes in the input, but that is rather tricky to do correctly.

I've taken out the alert(); a malformed expression would probably be better handled by the caller.