Mirko Mukaetov
Mirko Mukaetov

Reputation: 204

Apend string to url using jQuery

I want to check if url of the website not contain ?lang=en ex.

mywebsite.com

to append mywebsite.com?lang=en using jQuery

Can someone pls give me example how to do this code.

Thanks,

Upvotes: 1

Views: 264

Answers (3)

kayen
kayen

Reputation: 4868

// Check the query portion of the URL
if ( !location.search ) location.search = 'lang=en';
// If it has a query string, and not lang=en then - 
else if ( !location.search.match(/lang\=en/g) ) location.search+= '&lang=en';

Upvotes: 2

radia
radia

Reputation: 1486

Here's a function i'm using in my current project, I don't remember the source where i found it but hope it can help:

function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
if (url.indexOf(paramName + "=") >= 0)
{
    var prefix = url.substring(0, url.indexOf(paramName));
    var suffix = url.substring(url.indexOf(paramName)).substring(url.indexOf("=") + 1);
    suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
    url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
    url += "?" + paramName + "=" + paramValue;
else
    url += "&" + paramName + "=" + paramValue;
}
window.location.href = url;
}
setGetParameter("lang","en")

Upvotes: 0

LJ Wadowski
LJ Wadowski

Reputation: 6718

if(window.location.href.indexOf('?lang=en') < 0){
   window.location.href = window.location.href + '?lang=en';
}

Upvotes: 1

Related Questions