Ilijanovic
Ilijanovic

Reputation: 14904

Split string by regex match

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

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You need to

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

anubhava
anubhava

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 position

Upvotes: 2

Related Questions