skip to Main Content

I’m working on a web app where users can create text templates. For example when the user is creating a new template they would write any variable text like so [[variable]].

Example:

Hi [[recipient]],

Here are your login credentials:

Username: [username]

Password: [[password]]

When the user submits the template form I need to search through the content string and get all the variables that they created and put them in an array. So for this example I’m trying to get an array that looks like this:

[recipient,username,password]

3

Answers


  1. Following regexp /(?<=[[).*?(?=]])/g will do the trick.
    Explanation:

    • (?<=[[) – positive lookbehind to match anything thats starts with [[, not including it.
    • .*? – match anything between (including empty string).
    • (?=]]) – positive lookahead to match anything thats ends with ]], not including it.

    Here is an example:

    const text = `Hi [[recipient]],
    Here are your login credentials:
    Username: [[username]]
    Password: [[password]]`
    
    const matchedParams = text.match(/(?<=[[).*?(?=]])/g)
    console.log(matchedParams)
    Login or Signup to reply.
  2. We can simply use lookarounds:

    const input = `Hi [[recipient]],
    
    Here are your login credentials:
    
    Username: [[username]]
    
    Password: [[password]]`
    
    const matches = [...(input.match(/(?<=[[).*?(?=]])/g) || [])]
    console.log(matches)

    In JavaScript it’s also simple to replace the values if you need to with the built-in replace function:

    const input = `Hi [[recipient]],
    
    Here are your login credentials:
    
    Username: [[username]]
    
    Password: [[password]]`
    
    function replace(input, map) {
      return input.replace(/[[.*?]]/g, val => map[val.slice(2, -2)])
    }
    
    console.log(replace(input, { recipient: "Bob", username: "b00", password: "12345" }))
    Login or Signup to reply.
  3. You can use a simple regex and map with slice remove [[ and ]] from results

    const grabVals = (str) => (str.match(/[[(w+)]]/g) || []).map(el => el.slice(2, -2));
    const str = `Hi [[recipient]],
    
    Here are your login credentials:
    
    Username: [[username]]
    
    Password: [[password]]`;
    const vals = grabVals(str);
    
    console.log(vals);

    Regex explaination:

    [[ – matches string "[["

    (w+) – matches any word characters

    ]] – matches string "]]"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search