Moshe Shaham
Moshe Shaham

Reputation: 15974

Split string with tags using regular expressions

I would like to split this kind of texts in the following manner:

"string1<%string2%>string3"   => [string1, <%string2%>, string3]
"string1<%string2%><%string3%>"   => [string1, <%string2%>, <%string3%>]

How can this be done with regular expressions?

Upvotes: 1

Views: 71

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

Here is a way:

alert("string1<%string2%><%string3%>".split(/(<%.*?%>)/).filter(Boolean));

The (<%.*?%>) regex matches <%...%>-like entities, and captures them so that they are preserved in the resulting array. An alternative regex can also be (<%(?!%>).*?%>).

With .filter(Boolean) you will be able to get rid of any empty array elements.

In case there are no spaces inside <%...%>, you can use (<%\S+%>) regex.

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56809

Assuming that < and > does not appear in the text outside <% and %>, you can use match instead:

"string1<%string2%><%string3%>string4".match(/[^<>]+|<%.*?%>/g)
>>> ["string1", "<%string2%>", "<%string3%>", "string4"]

Upvotes: 2

anubhava
anubhava

Reputation: 785058

You can do:

var re = /(<%[^%]*%>)/;
var m = "string1<%string2%><%string3%>".split(re).filter(Boolean);
//=> ["string1", "<%string2%>", "<%string3%>"]

var m = "string1<%string2%>string3".split(re).filter(Boolean);
//=> ["string1", "<%string2%>", "string3"]

Upvotes: 0

Related Questions