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
Hi Astur103, I seldom play with regex but just maybe following may help: var regexVar = new RegExp('^\\w{' + characterLength + '}\_'); Code (JavaScript):
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,