简体   繁体   English

使用Java脚本提取a href路径的一部分

[英]Extracting a portion of the a href path using Javascript

I'm needing to extract a portion of an href attribute using javascript. 我需要使用javascript提取href属性的一部分。

I've come up with a solution, but I'm not sure it's the best way. 我已经提出了一个解决方案,但是我不确定这是最好的方法。 Below is my sample code. 以下是我的示例代码。 I've got a variable with the complete href path -- and all I'm interesting in extracting is the "Subcategory-Foobaz" portion. 我有一个带有完整href路径的变量-我感兴趣的是提取“ Subcategory-Foobaz”部分。

I can assume it will always be sandwiched between the 2nd "/" and the "?" 我可以假设它将始终夹在第二个“ /”和“?”之间 .

I'm terrible with Regex, so I came up with what seems like a hokie solution using 2 "splits". 我对Regex感到很糟糕,所以我想出了使用2个“拆分”的hokie解决方案。

var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/")[2].split("?")[0];
console.log(subcat);

Is this horrible? 这很恐怖吗? How would you do it? 你会怎么做?

Thanks 谢谢

re      = /\/[^\/]+\/([^?]+)/;
str     = '/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about';
matches = str.match(re);
console.log(matches);
var path = "/Category-Foobar/Subcategory-Foobaz?cm_sp=a-bunch-of-junk-i-dont-care-about";
var subcat = path.split("/").pop().split("?")[0];
console.log(subcat);

Just a small change; 只是一个小小的改变; use pop() to get the last element no matter how many /'s you have in your string 使用pop()获取最后一个元素,无论您的字符串中有多少个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM