-1

I used the slice() method to test to see if the contents of a variable was in a main string.

I was trying to use a regex. But, I could not figure out how to put the variable inside the regex.

Here is what I did:

    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.";
    }

Here is what I wanted to do instead. I wanted to use the variable "head" where I have the text "head".

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

// Verify if the 1st string starts with the 2nd string, 
var TF = /^head/.test(mainStr);

if(TF === false){
    return "Incomplete.";
}

If I could use a variable in what is being searched for, I could use the same technique for finding the body inside the mainStr and the tail at the end. I am looking for the technique and not just the solution to this particular project.

1 Answers1

2

You can compile a regexp from a string. Try this:

var regexp = new RegExp("^" + head);
var TF = regexp.test(mainStr);
Derek Hopper
  • 1,862
  • 9
  • 19