Variable inside Regex

Hi everyone,

I am trying to put inside a regex a variable but I cannot get the right results I want.

I want to remove 40 characters from the string “stringToSend”, but if I add the variable “characterLength” inside the regex, it doesn’t work.

If I just add the integer 40 inside the regex, everything works fine.

How can I add that variable “characterLength” inside the regex rightly?

    var stringToSend = '9615f3837cf791fc4302a00ab4adb32dd4171b1e_00004.jpg';
    var characterLength = 40;
    var regexVar = new RegExp(/^\w{' + characterLength + '}\_/);  // this regex doesn't work
    // var regexVar = new RegExp(/^\w{40}\_/); // this regex is working
    outputString = stringToSend.replace(regexVar, '');
    outputString = outputString.replace(/\.[^/.]+$/, '');

    console.log(outputString); // Wanted output: 00004

Thank you very much in advance,

This would work:

var regexVar = new RegExp(`^\\w{${characterLength}}\\_`); 

In your example you hand the RegExp just an already formatted regular expression.

In mine I hand it a string, or to be more specific I hand it a template literal which the constructor can use to make a regular expression. Template literals allow for embedded expression inside ${}.

Thank you very much. It worked fine!!


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.