1

I'm still learning and although my method works, I'm not convinced it's elegant and could be improved. Basically we have a system where I CAN'T control the output so I'm using the following code to get the href of an anchor and manipulate it to point to the correct place.

HTML

<a class="shop-return" href="/_shop/category/prodect/">Link</a>

jQuery

//set url object
var link = $(".shop-return");
//get url objects href value + split it into parts
var linkUrl = link.attr("href").split("/");
    /*remove the starting blank space and the ending 
    product part of url*/
    linkUrl.splice(-2,2)
    linkUrl.shift();

//build new link
var newLinkUrl = linkUrl.join("/");
//set new link on object
link.attr('href', "/" + newLinkUrl + "/");

Any suggestions on how to make this cleaner / more efficient - and if I've gone about things in the right away or not would be appreciated.

1 Answer 1

2

An alternative is to use regular expressions to shorten the code a little:

var link =  $(".shop-return");
var linkUrl = link.attr("href").match(/\/([_a-z]+)\/([a-z]+)\//);

link.attr('href', linkUrl[0]);

This uses regEx matches. linkUrl[0] contains the url with the prefix and suffix slash '/' on, linkUrl[1] is the first url part, linkUrl[2] the second

Having brackets in the regex selects what the 'matches' are, so: link.attr("href").match(/\/([_a-z]+)\/([a-z]+)\//);

returns ["/_shop/category/", "_shop", "category"]

Sign up to request clarification or add additional context in comments.

2 Comments

Nice! So the match, can you explain what this is doing - guessing it's making an array of the URL parts?
Yes that's right, have added a short explanation to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.