This is driving me bonkers.
I have an ebay store menu which is created dynamically via php.
The urls look like this:
.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: /
I've made a fiddle here: /
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.
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/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.
Share Improve this question asked Jun 10, 2013 at 11:39 lharbylharby 3,2776 gold badges26 silver badges65 bronze badges 06 Answers
Reset to default 3Straight 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
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]
All you're missing is an assignment operator
$href = $href.split('_')[0];
You need to assign the result of the split operation to a variable to use it later on.
var href = $(this).attr('href');
href = href.split('_')[0];
console.log(href);
http://jsfiddle/HA793/5/
Additionally I'd suggest to only use the $ variable name prefix, when the result is actually a jQuery object.
You should assign result of split to your variable $href:
$('.MenuItem a:odd').each(function() {
var $href = $(this).attr('href');
$href = $href.split('_')[0] + $href.split('_')[1];
console.log($href);
Consider using this function: http://php/manual/en/function.parse-url.php