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
    Possible duplicate of [Escape string for use in Javascript regex](https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) – Andreas Aug 21 '18 at 15:31

3 Answers3

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

Georgy
  • 2,002
  • 2
  • 17
  • 31
  • 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 – Hugo Delannoy Aug 21 '18 at 15:54
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"));
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}"
ykit9
  • 446
  • 4
  • 7