-2

I have a string like this:

let temp = 'Hi {{username}}, Your request with request id: {{requestId}} has been processed. Please contact your nearest shop.'

I want this array from the string:

['userName', 'requestId']

I know I have to somehow use regular expressions to achieve this but I can't figure out the pattern for achieving this.

NOTE: This is just an example string and I want a more general approach to solve this problem coz the string may vary.

Abhishek
  • 113
  • 3
  • 12
  • 1
    whats about `{{(.*?)}}`. i do not have any experience with javascript, but on some languages it works – D-E-N Sep 30 '20 at 17:23
  • Output is coming with the brackets included. I don't want the brackets @D-E-N – Abhishek Sep 30 '20 at 17:27
  • You can simply add a capture group: `{{(.*?)}}` – jrook Sep 30 '20 at 17:34
  • Please either update your question to match the answer you accepted or un-accept the answer. It does not satisfy your requirement that **the string may vary**. – jrook Sep 30 '20 at 17:59

1 Answers1

-1

You need to use positive lookahead. Here is the regex which works for your case.

let temp = 'Hi {{username}}, Your request with request id: {{requestId}} has been processed. Please contact your nearest shop.'
temp.match(/(?<={{)(\w+)(?=}})/g)
Kritarth
  • 22
  • 2
  • Great! It works – Abhishek Sep 30 '20 at 17:33
  • This won't match if there are whitespaces in the string in the brackets. – jrook Sep 30 '20 at 17:35
  • @jrook The main task here is to avoid getting the curly braces in the final matches. Everything else can be adjusted as needed by the OP. – Kritarth Sep 30 '20 at 17:43
  • 1
    You can use `/(?<={{\s*)[\w\$]+(?=\s*}})/g` as a more comprehensive check that will extract any reasonable variable names, even if there is whitespace around them. – BadHorsie Sep 30 '20 at 17:48
  • 1
    @Kritarth The OP states (in bold font) that the string inside those brackets **may vary**. Your solution simply does not satisfy that requirement. Even if it works for the OP, it does not change the fact that this is a wrong answer to the question asked. – jrook Sep 30 '20 at 17:52
  • 1
    And it is not just whitespaces. Characters such as `|` , `$` , or `-` will break this regex. `$` is a valid character in JavaScript variable name. – jrook Sep 30 '20 at 17:54
  • @jrook The main goal was to extract the string present inside {{ }} and the solution is correct except the fact mentioned by you about the whitespace – Abhishek Oct 01 '20 at 14:37