Reputation: 63
Question:
Given this string:
str = "this is<< just>> an example <<sentence>>"
How do you get the following array:
arr = ["this is", "<< just>>", " an example ", "<<sentence>>"]
Attempts:
I can split the string, however this removes the '<<' and '>>'.
str.split(/<<|>>/)
=> ["this is", " just", " an example ", "sentence"]
I can match the text blocks of text between and including '<<' and '>>', however this is missing the rest of the sentence.
str.match(/(<{2})(.*?>{2})/g)
=> ["<< just>>", "<<sentence>>"]
How do you capture the rest of the string as well as separate capture groups?
Upvotes: 3
Views: 267
Reputation: 15629
Simple solution - add the matching groups to your split regex
var str = "this is<< just>> an example <<sentence>>"
var result = str.split(/(<<|>>)/)
console.log(result);
or if you want the <<>>
to be included, add them to your matching group
/(<<[^>]+>>)/
Upvotes: 1
Reputation: 2905
Split by <<...>>
and use .filter(Boolean)
to filter out empty values.
const str = "this is<< just>> an example <<sentence>>"
const r = str.split(/(<<[^<>]+>>)/g).filter(Boolean)
console.log(r)
Upvotes: 1
Reputation: 1764
Split by <<...>>
const str = "this is<< just>> an example <<sentence>>"
const r = str.split(/(<<[^<>]+>>)/g)
console.log(r)
Upvotes: 1
Reputation: 370679
Here's one option - match <<
up to and including >>
, OR match characters up to the point where lookahead matches <<
or the end of the string:
const str = "this is<< just>> an example <<sentence>> foo";
const re = /<<.+?>>|.+?(?=<<|$)/g;
console.log(str.match(re));
Upvotes: 4