/    Sign up×
Community /Pin to ProfileBookmark

Variable inside a regex

Hi all,

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?

[code]
<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]

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJun 22.2021 — How about using the string format, something like:
[code=javascript]
var regexVar = new RegExp('^w{' + characterLength + '}_');
[/code]

Warning: I am definitely not a JavaScript expert, just going by what I found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions :)
×

Success!

Help @astur103 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...