是否有任何方法可以返回拆分操作中被丢弃的部分

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

本文关键字:操作 拆分 任何 方法 返回 是否      更新时间:2023-09-26

我正在构建一个基本的应用程序,它允许用户在使用Javascript中的#参数的会话之间共享或继续他们的搜索状态(我将其构建为SPA,因此GET参数不一定总是有效的)。

在我的应用程序中,我可以有一个URI,比如:/items#rarity=rare,common,uncommon&cost=ascending&category=primary

如果我想检查在react组件中设置成本过滤器的状态,我想提取asecnding,然后选中升序复选框来设置页面加载的状态。

如果我将Javascript的split函数与regex结合使用,我可以通过以下操作捕获所有关于成本的信息:

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

现在,这显然将返回一个分为两部分的数组,第一部分是/items#rarity=rare,common,uncommon&category=primary,因为split函数将根据所提供的条件进行拆分,在我的情况下,该条件与regex中的字符串匹配。

有没有什么方法可以从split函数中捕获提取的字符串,这样我就可以解析成本字符串?

不可能。哦,有!只需将正则表达式封装在捕获组中即可。

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]);

要实现预期结果,请使用以下

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