0

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 ;
}

4 Answers 4

1

window.location is actually an object, it has a 'search' property that make it easier to parse the query string.

function getParam(param){
    var qs = window.location.search.substring(1).split('&');
    var qsp;
    for (p in qs){
        qsp = qs[p].split('=');
        if (qsp[0] == param) return qsp[1]; 
    }
    return null;
}

to check for a specific parameter :

var value = getParam('name');
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

7 Comments

My 2nd problem is, let says the URL already pass the lang variable, something like this (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 (index.php?id=23&lang=en&lang=jp)
@MiszJieha This is exactly what the second part is all about. What it does: It takes the query-string (in document.location.search), splits it in pairs, which are then stored as key-value associations in the object "params". (So there will be param.id == "23", param.lang == "jp", etc.) Now we just overwrite "param.lang" (anyway, if it has been set before or not). Then we compose a clean, new url by assembling the parts of the base-url (minus the search-part or any hash-marks) and add the new query-string to it (joined from the key-value pairs in the "params" object).
Continued -- The beauty of it: Once we reach params.lang = newval;, you can set any params you would like to set or clear any params (e.g. clearing "page" would be delete params.page). It works, regardless, if there have been any parameters set at all or not, just the same.
FYI i'm new in javascript, i just wonder where should i put that coding. My working coding as per edited on my post. should i put after var url...and what does self. mean?
I've just put the code in a function. self refers to the global context, in the browser it is just the same as window (but it's a bit more general). On the location-object: location.href is the same as the sum of its following parts: location.protocol (e.g.: "http:"), "//", location.host (e.g.: "stackoverflow.com"), location.pathname (e.g.: "/questions/18995929/..."), location.search (e.g: "?lang=en") and location.hash (e.g.: "#18996039"). (Or short: href = protocol+"//"+host+pathname+search+hash, where search is the query-string including the "?" or empty.)
|
0

You can simply use indexOf() method for this

if(window.location.href.indexOf("your value") != -1) {
     alert("It contains");
 }
 else {
    alert("Nope");
 }

Comments

0
function menu_goto(newvalue)
        {
        var baseurl = window.location.href ;
        var langwithpara = "&lang=" + newvalue;
        var langwopara = "?lang=" + newvalue;

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

1 Comment

My 2nd problem is, let says the URL already pass the lang variable, something like this (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 (index.php?id=23&lang=en&lang=jp)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.