0

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: /items#rarity=rare,common,uncommon&cost=ascending&category=primary

If I wanted to check what state to set the cost filter in my react component, I'd want to extract asecnding 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 /items#rarity=rare,common,uncommon& and category=primary 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?

Halfpint
  • 3,967
  • 9
  • 50
  • 92

2 Answers2

2

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[0]);
console.log(r[1]); //there is the "thrown" part
console.log(r[2]);
nicael
  • 18,550
  • 13
  • 57
  • 90
1

To achieve expected result, use below

var x="/items#rarity=rare,common,uncommon&cost=ascending&category=primary";

console.log(x.split('cost=')[1].substring(0,x.split('cost=')[1].indexOf("&")));

http://codepen.io/nagasai/pen/RRyLmA

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40