1

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?

1

3 Answers 3

0
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}"

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I'm stupid... I trust the Firefox console return when I press enter. Witch return me "\\newcommand{\\hello}{@replace}" but when print it with console.log it's works ! Thanks
0

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"));

Comments

0

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}"

1 Comment

You right! I focused on RegExp but your solution also works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.