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
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:
We can simply use lookarounds:
In JavaScript it’s also simple to replace the values if you need to with the built-in replace function:
You can use a simple regex and
map
withslice
remove[[
and]]
from resultsRegex explaination:
[[
– matches string "[["(w+)
– matches any word characters]]
– matches string "]]"