dzordz
dzordz

Reputation: 2317

Split string into array between to characters?

So I'm trying to split string that I have in some not regular way. I tried to do something with regular expressions but I'm not so much into regex to invent something like that.

Basically I have a string that look like this:

var links = "<a>4</a><b><c><d><e><f>";

And I wanna use a .split() js method to recieve them in array like so:

["<a>4</a>", "<b>", "<c>", "<d>", "<e>", "<f>"]

So it's obviously that I need to split them on >< characthers but if I do this:

links.split("><");

They are gonna split in the way I wanna but I'm gonna loose the > and < signs. example:

["<a>4</a", "b", "c", "d", "e", "f>"]

This is not good solution for me.

So basically my question is: Is it possible to make some kind solution with regex or something else to get array result as I imagined?

Upvotes: 1

Views: 66

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382112

A quick and clean method would be to use match instead of split :

var matches = links.match(/<.+?>(?=<|$)/g)

For your string it gives

["<a>4</a>", "<b>", "<c>", "<d>", "<e>", "<f>"]

Be careful that using regular expressions with a non regular language like HTML is dangerous. It's often OK for simple things but it's also limited and you may encounter surprises, for example if you want to apply it to nested elements.

Upvotes: 2

Cerbrus
Cerbrus

Reputation: 72857

A quick'n dirty method would be to add a delimiter between the ><, with a regex replace, and then to split on that delimiter:

var links = "<a>4</a><b><c><d><e><f>";
links.replace(/></g, '>|<').split('|');

Result:

["<a>4</a>", "<b>", "<c>", "<d>", "<e>", "<f>"]

Just make sure the delimiter you chose doesn't occur in the string itself.
(You can use longer strings as delimiters, like: "|-|".)

Upvotes: 1

Related Questions