Reputation: 14904
I have this following problem. i try to split a string up depending on a regex.
I want to to split it by {{ name }}
, {{ age }}
and so on.
The expected output should look like this:
["hy my name is: ", "{{ name }}", " and i am ", "{{ age }}", " old"]
My current attempt was this here:
let str = "hy my name is: {{ name }} and i am {{ age }} old";
let vars = str.split(/({{)(.*)(}})/);
console.log(vars);
Whats the correct regex for this task?
Upvotes: 2
Views: 1552
Reputation: 626870
You need to
split
if it is captured: "If separator is a regular expression that contains capturing parentheses (), matched results are included in the array.".
, .*?
, instead of the greedy .*
. Otherwise, the {{.*}}
will match {{
, then any 0 or more chars other than line break chars as many as possible, and then }}
, so all {{...}}
substrings in between {{
and }}
will be put into one match.JS fixed demo:
let str = "hy my name is: {{ name }} and i am {{ age }} old";
let vars = str.split(/({{.*?}})/);
console.log(vars);
// => [ "hy my name is: ", "{{ name }}", " and i am ", "{{ age }}", " old"]
Note that {
and }
are only special if there is a number inside, like {6}
. In {{.*?}}
, the curly braces cannot be parsed as limiting quantifiers since there is no number, hence, you may escape {
chars in order to prevent any ambiguity.
Also, in case you have a match at the start of the string, you will have an empty element in the resulting array, then you need to remove the empty elements:
str.split(/({{.*?}})/).filter(Boolean)
Upvotes: 3
Reputation: 785196
Instead of split
, you may use this regex with match
:
/{{.*?}}|.+?(?={{|$)/g
Code:
let str = "hy my name is: {{ name }} and i am {{ age }} old";
let vars = str.match(/{{.*?}}|.+?(?={{|$)/g);
console.log(vars);
RegEx Details:
{{.*?}}
: Match a string within {{...}}
|
: OR.+?
: Match 1+ of any character that satisfies next lookahead condition(?={{|$)
: Positive lookahead condition that makes sure that we have wither {{
or end of line at next positionUpvotes: 2