2

i have a code which is avaliable in the following fiddle

http://jsfiddle.net/wbagktuw/

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

1
  • I assume the page number's not always 2? Commented May 20, 2015 at 20:14

4 Answers 4

4

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, '');
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the best solution without involving any 3rd party library to parse the URL
0

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/

Comments

0

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

2 Comments

what if &pagenum=3 ?
In that case you can use regex. I didn't know that might change. You could write a regex query that checks for if &pagenum= followed by a number exists
0

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);
});

3 Comments

What if pagenum=2 is not the last param? and it's before rpttype for example?
Edited to account for that
Edited incase there are params with practicaly the same name

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.