Reputation: 73
I'm trying to use regex in a Nodejs app. I usually use it in Python and it seems to have some differences.
Here is the problem :
I have this string \newcommand{\hello}{@replace}
and I want to replace @replace
by REPLACED
in the second curly bracelets ONLY when I found \hello
in the first curly bracelets. So the expected result is : \newcommand{\hello}{REPLACED}
I try this:
r = new RegExp('\\newcommand{\\hello}{(.*?)}');
s = '\\newcommand{\\hello}{@replace}';
s.replace(r, 'REPLACED');
But nothing is replaced... any clue?
Upvotes: 1
Views: 60
Reputation: 2462
r = new RegExp(/\\newcommand{\\hello}{@replace}/);
s = '\\newcommand{\\hello}{@replace}';
let a = s.replace(r, '\\newcommand{\\hello}{REPLACED}');
console.log(a)
Output would be : "\newcommand{\hello}{REPLACED}"
Upvotes: 1
Reputation: 493
You don't need regex at all to perform this kind of operation. You can simply use string at first parameter:
s = '\\newcommand{\\hello}{@replace}';
s.replace('@replace', 'REPLACED'); // => "\newcommand{\hello}{REPLACED}"
Upvotes: 0
Reputation: 538
I'm not sure if I understood the question correctly. Is this what you're looking for?
function replaceWith(myReplacement) {
var original = "\\newcommand{\\hello}{@replace}";
var regex = "{\\hello}{@replace}";
return original.replace(regex, `{\\hello}{${myReplacement}}`)
};
console.log(replaceWith("World"));
Upvotes: 0