Alex Alex - 1 year ago 41
Javascript Question

Is there any way to return the thrown away part of the split operation?

I'm building a basic application which lets the user to share or continue their search status between sessions with # parameters in Javascript (I'm building this as a SPA so GET parameters won't always necessarily work).

In my app I could have a URI like:


If I wanted to check what state to set the cost filter in my react component, I'd want to extract
and then check the ascending checkbox to set the state on page load.

If I use Javascript's split function combined with regex, I can capture all information on cost by doing:

var hash = window.location.hash;
hash = hash.split(/cost.*&/);

Right now, this will obviously return an array in two parts the first being
as the split function will split on the condition supplied which in my case matches the string from regex.

Is there any way I can capture the extracted string from the split function so I can then parse the cost string?

Answer Source

No way. Oh, there is! Just wrap your regex in the capture group.

var s = '/items#rarity=rare,common,uncommon&cost=ascending&category=primary';
r = s.split(/(cost.*&)/);

console.log(r[1]); //there is the "thrown" part