svprdga
svprdga

Reputation: 2569

Update URL parameter with javascript/jquery with a regEx

I have a web with an URL like that:

http://www.example.com/index.php?mod=7&sec=franquicias&month=10&year=2013

Inside, there is a date selector; which is supposed to change the get param month and year; and then reload the page.

From HTML, I do the following in the button in charge of decreasing the date:

<button type="button" class="btnIcon previous lbutton" onclick="changeMonth('previous',{$smarty.get.month},{$smarty.get.year})">

And the javascript function that has to manage with that is:

    function changeMonth(changeType, month, year){
    changeMonth;

    switch (changeType){
    case "previous":
        changeMonth = month-1;
        if (changeMonth <= 0) changeMonth = 12;
        if (changeMonth < 10) changeMonth = "0"+changeMonth;
        window.location = updateURLParameter($(location).attr('href'), month, changeMonth);
        break;
    case "next":
        break;
    }       
}

function updateURLParameter(url, param, paramVal){

    var regEx = /month=[0-9]{3}/;
    console.log("paramVal: "+paramVal);
            // paramVal here is ever correct.
    var newUrl = url.replace(regEx, 'month='+paramVal);

    console.log(newUrl);
    return newUrl;
}

It appears that it should work, now the strange thing is that only works when GET param in url is &month=03, when there are other month, url.replace doesn't replace the url correctly. It is important to note that 'paramVal' in function 'updateUrlParameter' it's always correct; so the problem it's in urlReplace from 'function updateUrlParameter'.

I appreciate any help.

Upvotes: 0

Views: 226

Answers (1)

Barmar
Barmar

Reputation: 782717

I don't see how it can work even for month=03. [0-9]{3} matches exactly 3 digits, and 03 doesn't match that. The correct regexp is:

/\bmonth=\d{2}\b/

Upvotes: 1

Related Questions