How do i pass a variable in regex

Tell us what’s happening:

str.replace(/(?=${before})(\w+)/,after); Here the before (string literals) is not working. I want my regex to take value inside the before variable directly to regex. How can i do it

Your code so far


function myReplace(str, before, after) {

 let regex=`/(?=<before>)(\w+)/`;
 let replacedStr = str.replace(regex,after);
 
 return replacedStr;
// let re = new RegExp(regex,"g");

 //return str.replace(/(?=${before})(\w+)/,after);
 
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Search and Replace

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace

I tired changing my code still the variable before is somehow is not reading it value.

function myReplace(str, before, after) {


    let re = new RegExp("/"+before+"/", "g");
    return str.replace(re,after);
  
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));

//A quick brown fox jumped over the lazy dog

Thanks it worked.

Mr RandellDawson I want to ask you one question let re = new RegExp("\\b(" + before + ")\\b","g");

An explanation was given as When creating the \b boundary markers, we have to use two backslashes because we are writing them in a normal string, not a slash-enclosed regular expression. Can you explain in simple words what is happening here

Anytime you use a special meta character like \s or \w or \b, you must add the extra backslash for the string version of the regular expression to work with RegExp.

In regular expressions, the ** is an escape character in string literals, so you must escape the single ** with another \ so that the actual regular expression sees the single ** with the character that follows it.

3 Likes

Thank you so much,it helped alot

can you please guide me what is the function of `` in RegExp such as used above-quoted example

let regex=`/(?=<before>)(\w+)/`;