Misz Jieha Misz Jieha - 15 days ago 9
Javascript Question

Check if URL pass variable using JavaScript

How can I check if URL contains variable or not? I have my function like this

My 2nd problem is, let says the URL already pass the lang variable, something like this (http://index.php?id=23&lang=en) i want that when they run this function again it will replace the lang variable to the new on instead of add new lang variable like this (http://index.php?id=23&lang=en&lang=jp)

function menu_goto(newvalue)
{
var baseurl = window.location.href ;

var langwithpara = "&lang=" + newvalue;
var langwopara = "?lang=" + newvalue;

if (newvalue != 0) {
if(baseurl.match(/?/)){
alert ('123');
location.href = baseurl + langwithpara ;
}
else{
alert ('456');
location.href = baseurl + langwopara ;
}
}
}


My new coding (work)

function menu_goto(newvalue)
{
var baseurl = window.location.href ;
var url = baseurl + ( (baseurl.match(/\?/))? '&':'?' ) + 'lang=' + newvalue;

location.href = url ;
}

Answer

the problem is probably the missing escaping of "?" in your RegExp:

if (baseurl.match(/\?/)) { // ...

a bit shorter would be:

var url = baseurl + ( (baseurl.match(/\?/))? '&':'?' ) + 'lang=' + newvalue;

You would probably want to clean any param "lang" before, so it doesn't become an array by multiple occurrence.

It would probably better to assemble the url anew like

function menu_goto(newvalue) {
    var params = {};
    if (self.location.search) {
      var pairs = self.location.search.substring(1).split("&"); // skip the "?"
      for (var i = 0; i < pairs.length; i++) {
        var parts = pairs[i].split('=');
        params[parts[0]] = parts[1];
      }
    }
    params.lang = newvalue;
    var query = new Array();
    for (var p in params) query.push(p + '=' + params[p]);
    var url = self.location.protocol + '//' + self.location.host + self.location.pathname
              + '?' + query.join('&');

    self.location.href = url;
}

Here is yet another solution using RegExps:

function menu_goto2(newvalue) {
    var url = self.location.href;
    url = url.replace(/#.*/, ''); // clean any hash at end
    url = url.replace(/[&\?]lang=[^&]*/, ''); // clean any param lang and its value
    // we might have had two or more params and "lang" was the first one
    // then we might have lost the "?" => replace first "&" by "?"
    if (url.indexOf('?') < 0 && url.indexOf('&') >= 0) url = url.replace(/&/, '?');
    url += ( url.match(/\?/)? '&':'?') + 'lang=' + newvalue; // add the new param lang
    self.location.href = url;
}

Which could be shortened to

function menu_goto3(newvalue) {
    var url = self.location.href.replace(/#.*/, '').replace(/[&\?]lang=[^&]*/, '');
    if (url.indexOf('?') < 0 && url.indexOf('&') >= 0) url = url.replace(/&/, '?');
    url += ( url.match(/\?/)? '&':'?') + 'lang=' + newvalue;
    self.location.href = url;
}