Reputation: 691
I am trying to build a Regex for a split in Javascript that will split a string on every position where there are braces with text inside {t}.
The problem I have is the Regex expression. At the moment I have a Regex expression that matches the braces {}, but when I split the string on these braces, the braces will have been removed by the split function.
So imagine I have a string: "My name is {name} and I am {years} old". On that String I will use the expression below:
const splitted = value.split(/[{}]+/g); // Value is "My name is {name} and I am {years} old"
console.log(splitted);
Above console.log shows
["My name is ,", "name", " and I am ", "years", " old"]
But I want
["My name is ,", "{name}", " and I am ", "{years}", " old"]
What am I doing wrong?
Upvotes: 1
Views: 49
Reputation: 92
We can use lazy Quantifier for this.
const s = "My name is {name} and I am {years} old";
var arr = s.split(/({[^]*?})/g);
console.log(arr);
Lazy quantifier *?
gives you the shortest match that fits the regex.
Upvotes: 1
Reputation: 785098
You may use this regex with a capture group:
const s = "My name is {name} and I am {years} old";
var arr = s.split(/({[^}]*})/g);
console.log(arr);
{[^}]*}
matches a substring that starts with {
and ends with }
and by putting a capture group around this pattern we ensure that this group is part of the split
result.
Upvotes: 2