0

I have a template string for example:

`https://example.api/${id2}/pictures/${id}`

I need to convert it into another string with argument names and not actual values. Output should look like this:

"https://example.api/id2/pictures/id"

Is there a way of doing it?

Ilya G
  • 447
  • 2
  • 7
  • 17
  • See [Defer execution for ES6 Template Literals](/q/22607806/4642212). – Sebastian Simon Oct 19 '22 at 19:20
  • Does this answer your question? [Convert a string to a template string](https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string) – Filip Zieliński Oct 19 '22 at 19:20
  • "*I have a template string*" - no, you have a string, created from a template string expression. Assuming you had set up the variables `const id2 = 'id2', id = 'id';`, you already have exactly the string value that you want. – Bergi Oct 19 '22 at 19:55
  • @Bergi not really. If I do console.log(\`https://example.api/${id2}/pictures/${id}\`) I will get `"https://example.api/undefined/pictures/undefined"` – Ilya G Oct 19 '22 at 20:00
  • That's what I said. You need to define those two variables beforehand (with values other than `undefined`), then that statement will work exactly as expected. – Bergi Oct 19 '22 at 20:03
  • @Bergi but I don't need to get those values I need to get argument names instead of values for logging purposes – Ilya G Oct 19 '22 at 20:05
  • What arguments? What names? What logging? Please [edit] your question to show more of your code. – Bergi Oct 19 '22 at 20:06
  • I still don't get it. If you mean you want to get the code of the expressions you wrote inside the template interpolation parts, that is not possible. But why did you use a template string in the first place then? Just write the string that you expect to get directly. – Bergi Oct 19 '22 at 20:14
  • @Bergi Problem that I would like to solve here: I have const url = \`https://example.api/${id2}/pictures/${id}\` which we use in http request. But for logging purposes we need to log url without actual id's in this url so it should look like this 'https://example.api/id2/pictures/id'. So I'm looking at options how to do it – Ilya G Oct 19 '22 at 20:22
  • You can't. ``const url = `https://example.api/${id2}/pictures/${id}`;`` is no different from `const url = 'https://example.api/'+id2+'/pictures/'+id+'';` - all you got is a string value in the `url` variable. You can either use regex to replace all numbers with some placeholder for logging, or you can write your code in a manner so that you create two different strings - one for the http request and one for logging. They may share some code (put it into a function) or they may not. – Bergi Oct 19 '22 at 20:35

0 Answers0