cj333
cj333

Reputation: 2609

javascript, if current url withour request part

I want do something: if something type url address like: www.mydomain.com/search(without request part), I want do something with javascript, fill with the url like www.mydomain.com/search?search=car, but nothing happened in my code.

   <script>
    var curent_url = document.URL;
    if(document.URL.indexOf("?") < 0){ //if(!document.URL.match(/\?/)){
        //alert('ok');
        document.URL = curent_url+'?search=car';
    }
    </script>

Upvotes: 0

Views: 103

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270677

Instead of document.URL, check for an empty document.location.search:

if (document.location.search.length === 0) {
  // empty query string... append your part to doc
  document.location.href = document.location.href + "?search=car";
}

Examine the document.location object in your console to see what else it offers. There's usually no need to parse out document.URL or document.location.href directly.

console.dir(document.location);

Upvotes: 2

Related Questions