0

It feels like I've tried every single combination and Google search possible, yet I'm too dumb to figure out why this doesn't work as I want it to.

I'm trying to find all placeholders in my text, which follows the following format {var}.

const replacementKey = new RegExp(`{${placeholder}}`, 'g');

The regular expression above results in a 'SyntaxError: nothing to repeat'. The moment I change it into the following the error goes away:

const replacementKey = new RegExp(`{ ${placeholder}}`, 'g');

The regular expression that "works" results in a search for { var} instead of {var}, which obviously isn't going to work. I don't want that extra space there, but I don't seem to get it right. How do I identify all {var} in my strings, and why is that lack of space causing a syntax error?

Would appreciate any pointers I can get, and I'd love to understand why that syntax is causing the error it does.

  • 1
    Escape the string before using it in a regex. – Wiktor Stribiżew Oct 17 '22 at 08:24
  • Imho a better way would be to replace the placeholders with [`.replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace): `.replace(, )` with `` -> `/\{([^}]+)\}/g` and `` a function that returns the value the placeholder should be replaced with. – Andreas Oct 17 '22 at 08:32
  • @Andreas Sorry, yes, that's what I am doing already, replacing the placeholders using ````.replace()````. However, as described above, it's my regular expression that isn't working properly and therefore won't replace correctly. Your suggested regular expression will work as long as there's only one placeholder, I want to include a variable too for cases where there are multiple placeholders with different values. – Kriistoffer Oct 17 '22 at 08:36
  • Then why the `placeholder` part in the `replacementKey`? `"".replace(/\{([^}]+)\}/g, (_, placeholder) => placeholders[placeholder] || "")` – Andreas Oct 17 '22 at 08:42
  • @Andreas Because I want to replace all ````{0}```` with the value 100, and all ````{1}```` with the value of 'Ben', for example. In theory there will be different placeholders within those curly brackets, so I want to include a variable in the regular expression. It might not be the best solution, but I know it should work. What's inside the curly braces is important, which is why there needs to be a variable inside the regular expression. – Kriistoffer Oct 17 '22 at 08:49
  • That's the `placeholders[placeholder]` part. `placeholders` is an object: `{ "0", 100, "1": "Ben", "2": ..., ... }` – Andreas Oct 17 '22 at 09:14

0 Answers0