Andy Thomas
Andy Thomas

Reputation: 79

How to change the image when match the string in location path

I want to change my logo when the path have contain correct string, in the code bellow I tried to replace logo image to the new img when match the string: "?lang=ja" but not work

     var pathname = window.location.pathname;
     if(pathname.indexOf('?lang=ja') > -1){
       $("#logo img").attr("src", "http://demo-image-link.png");
     }     
});

Upvotes: 0

Views: 56

Answers (2)

Sudheer Donaboina
Sudheer Donaboina

Reputation: 416

It looks like you are trying to check the parameter in the URL.

window.location.pathname will only give the path of the URL (It does not include the parameters).

You can use either one of the below to get the parameters window.location.search --> returns all the parameters in the URL window.location.href --> returns the complete path including the parameters.

Upvotes: 1

Hossein Zare
Hossein Zare

Reputation: 580

Try this:

if (window.location.href.indexOf('?lang=ja') > -1) {
    $("#logo img").attr("src", "http://demo-image-link.png");
}     

Update:

let urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('lang') && urlParams.get('lang') === 'ja') {
    $("#logo img").attr("src", "http://demo-image-link.png");
}

Upvotes: 1

Related Questions