0

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?

<script>
    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
</script>
Mapg
  • 13
  • 3

0 Answers0