Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get all href urls in a document and truncate or split them

This is driving me bonkers.

I have an ebay store menu which is created dynamically via php.

The urls look like this:

 http://stores.ebay.co.uk/somestore/Golf-Shoes-/_i.html?_fsub=3831075010

There are several of these, and for some reason my split is not working, I am trying to remove the data after the last slash.

    $('.MenuItem a:odd').each(function() {
    var $href = $(this).attr('href');
    $href.split('_')[1];
    console.log($href);
});

By my logic that should return: http://stores.ebay.co.uk/somestore/Golf-Shoes-/

I've made a fiddle here: http://jsfiddle.net/lharby/HA793/1/

I cant be too far off. I've tried splitting by other characters too to test the theory, and nothing seems to work. Where am I going wrong.

like image 850
lharby Avatar asked Nov 16 '25 10:11

lharby


2 Answers

Straight out of the MDN documentation

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.

The split has no effect on the string it is splitting. Instead assign the first part of your split to a variable like so

var part = $href.split('_')[0];

You could also use the last slash as your point of reference like so

var part = $href.substring( 0, $href.lastIndexOf( '/' ) + 1 );

Fiddle here

like image 185
Bruno Avatar answered Nov 19 '25 01:11

Bruno


Try this:

$('.MenuItem a:odd').each(function () {
    var href = this.href.split('_')[0];
    console.log(href);
});

FIDDLE DEMO

  • Get the href using this.href
  • Split the href with the char '_'
  • Get the first part of the array using split('_')[0]
like image 26
palaѕн Avatar answered Nov 19 '25 01:11

palaѕн



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!