-1

How can implement a function that returns a list of characters between two characters?

const string = "My name is <<firstname>> and I am <<age>>";

const getVariables = (string) => { 
  // How do I implement?
}

console.log(getVariables(string));  // ['firstname', 'age']

PS: I realize there are multiple answers on how to do something similar, but all of them only work for getting first instance and not all occurrences.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Kingsley CA
  • 10,685
  • 10
  • 26
  • 39

3 Answers3

0

Assuming this is some kind of templating, you can proceed like this:

let format = (str, vars) => 
  str.replace(/<<(\w+)>>/g, (_, w) => vars[w]);
  
//

const tpl = "My name is <<firstname>> and I am <<age>>";

console.log(
  format(tpl, {firstname: 'Bob', age: 33})
)
gog
  • 10,367
  • 2
  • 24
  • 38
0

You could search for string which has the starting pattern and end pattern with look behind and look ahead.

const
    string = "My name is <<firstname>> and I am <<age>>",
    parts = string.match(/(?<=\<\<).*?(?=\>\>)/g);

console.log(parts);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You could use regex, group, matchAll and get the first group

const string = "My name is <<firstname>>, from <<place>>, and I am <<age>>"

const getVariables = string => {
  return [...string.matchAll(/<<(\w+)>>/g)].map(match => match[1])
}

console.log(getVariables(string))
hgb123
  • 13,869
  • 3
  • 20
  • 38