Variable inside Regex

Discussion in 'JavaScript' started by astur103, Jun 22, 2021.

  1. #1
    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?
    
    <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>
    
    Code (markup):
    Thank you very much in advance,
    Astur
     
    astur103, Jun 22, 2021 IP
  2. hdewantara

    hdewantara Well-Known Member

    Messages:
    538
    Likes Received:
    47
    Best Answers:
    25
    Trophy Points:
    155
    #2
    Hi Astur103,
    I seldom play with regex but just maybe following may help:
    
    
    var regexVar = new RegExp('^\\w{' + characterLength + '}\_');
    Code (JavaScript):
     
    hdewantara, Jun 22, 2021 IP
  3. astur103

    astur103 Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    Thank you very much. It worked fine!!

    I like yours more, but let add another way some user sent to me ...
    
    var regexVar = new RegExp(`^\\w{${characterLength}}\\_`);
    Code (JavaScript):
    Best,
     
    Last edited: Jun 24, 2021
    astur103, Jun 24, 2021 IP