Reputation: 21
i have a code which is avaliable in the following fiddle
code is like this
<a data-rel="http://mydomain.domian.com?z_9.asp&rpttype=298&sotBy=2sortOrder=1&pagenum=2">
$(document).ready(function() {
var urlval = $("a").attr('data-rel');
alert(urlval);
});
i am trying to remove the &pagenum=2 from the url if it exists, if it does not exists, then no problem, if exists, i want to remove that
what should i try here
Upvotes: 2
Views: 96
Reputation: 439
How about this, fiddle
$(document).ready(function() {
var urlval = $("a").attr('data-rel');
var length = urlval.length
var start = urlval.indexOf("&pagenum=");
if (start !== -1){
var next = urlval.indexOf("&",start+1);
next = (next !== -1)?next:length;
var res = urlval.substring(start, next);
urlval = urlval.replace(res, '');
}
alert(urlval);
});
Upvotes: 0
Reputation: 35670
Use a regular expression to replace &pagenum=
followed by any number of digits.
Also check for the case where pagenum
is the first parameter, in which case it follows a question mark instead of an ampersand:
var urlval = $('a').attr('data-rel').replace(/[\?&]pagenum=\d*/g, '');
Upvotes: 4
Reputation: 3591
Or even better, why not just use what JS already has built-in..
urlval = urlval.replace('&pagenum=2', '');
This will handle both the cases where &pagenum=2
is present and not
Upvotes: 0
Reputation: 2156
use this code
$(document).ready(function() {
var urlval = $("a").attr('data-rel');
if(urlval.indexOf("pagenum")>-1){
urlval=urlval.slice(0,urlval.lastIndexOf("&"));
console.log(urlval);
}
});
jsfiddle http://jsfiddle.net/wbagktuw/2/
Upvotes: 0