开发者

Extracting a portion of the a href path using Javascript

开发者 https://www.devze.com 2023-01-23 19:41 出处:网络
I\'m needing to extract a 开发者_StackOverflow社区portion of an href attribute using javascript.

I'm needing to extract a 开发者_StackOverflow社区portion of an href attribute using javascript.

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.

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".

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消