我有一个已放入变量url中的URL
var url = $(location).attr('href');
网址在/
上分割url_split = url.split("/")
所以我的数组结果可以是例如:
["http:", "", "axces.test", "nl", "categorie", "minibar", ""]
["http:", "", "axces.test", "nl", "categorie", "minibar", "wand", ""]
如何获取“类别”值之后的值。 因此,在两种情况下,我都希望在URL中使用值“ minibar”。
我知道我可以这样实现:
var param = url_split[5];
但是“类别”可能不在第五个位置。
答案 0 :(得分:2)
您可以使用Array#findIndex
获取数组中项categorie
的当前索引,然后获取下一个。
const url = 'http://axces.test/nl/categorie/minibar/wand',
splitted = url.split('/'),
categorieIndex = splitted.findIndex((item) => (item === 'categorie')),
isFound = (categorieIndex > -1);
console.log((isFound) ? splitted[categorieIndex + 1] : '"categorie" not found');
上面的代码段:
"categorie" not found
不在categorie
中,url
。categorie
中url
之后的下一项。undefined
之后没有任何项目,categorie
。