Search code examples
javascriptassignment-operator

window.location.href is not being modified


I have following code

    var windowHref = window.location.href;
    if (windowHref.includes('/project/')) {
        var splitURL = windowHref.split('/');
        window.location.href = windowHref.substring(0, windowHref.indexOf('#/project')) + '?projectId=' + splitURL[splitURL.length - 2];
    }
    window.location.reload(true);

Before execution of above code, the value of window.location.href is

https://localhost:44301/default.aspx#/project/16a76abd-5b5b-4c63-822f-2bfd7f133adc/home

and after execution, I want its value to be like

https://localhost:44301/default.aspx?projectId=16a76abd-5b5b-4c63-822f-2bfd7f133adc

but when the line

window.location.href = windowHref.substring(0,windowHref.indexOf('#/project')) + '?projectId=' + splitURL[splitURL.length - 2];

is executed, the window.location.href remains unchanged.

And the result of

windowHref.substring(0,windowHref.indexOf('#/project')) + '?projectId=' + splitURL[splitURL.length - 2];

is

https://localhost:44301/default.aspx?projectId=16a76abd-5b5b-4c63-822f-2bfd7f133adc

What am I doing wrong?


Solution

  • I would suggest remove the line window.location.reload(true); as it's unnecessary to redirect the client to new page when using window.location.href

    var href =  window.location.href; 
    var index = href.indexOf('#/project/');
    if(index!==-1){  
       var splitURL = href.substring(index,href.length).replace('#/project/','?projectId=').split('/');
       window.location.href = splitURL[0];
    }