JSFiddle - React, Tailwind, and code Playground

by secretgspot

HTML

<h1>get() URL variables in JavaScript</h1>
<h4>by DJMeu</h4>
-You can use "get(var)" to get a variable from the URL like in PHP.<br>
-You also can specify other string to get the variable with "get(var,string)" like the example.<br>
-If the URL or the string doesn´t contain any variable it will return "false".<br>
-If the variable doesn't match, it will return "undefined".<br>
-If you don't specify any variable and the URL or the string contains some variable, it will return "true" and it will return "false" if it doesn´t contain anything.<br><br>
Example url:&nbsp;<input id="url" value="http://www.youtube.com/watch?v=yey3JWKMlcE" size="44"/><br/>
Var to get:&nbsp;&nbsp;&nbsp;&nbsp;<input id="input" value="v" size="25"/>
<button onclick="document.getElementById('get').innerHTML='Var content is: '+get(document.getElementById('input').value,document.getElementById('url').value)">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;GET&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</button>
<div id="get"></div>

JavaScript

function get(variable,optionalurl){
  if(variable){
    var ruta=location.href;
    if(optionalurl) ruta=optionalurl;
    if(ruta.indexOf('?')!==-1){
      ruta=ruta.substring(ruta.indexOf('?')+1);
    }else{
      if(ruta.indexOf('#')!==-1){
        ruta=ruta.substring(ruta.indexOf('#')+1);
      }else return false;
    }

    if(ruta.length !== 0){
      if(ruta.indexOf(variable+'=') != -1){
        var posvar=ruta.indexOf(variable+'=')+variable.length;

        if(ruta.indexOf('&',posvar) != -1){
          posand=ruta.indexOf('&',posvar);
        }else{
          posand=ruta.length;
        }

        variable=ruta.substring(posvar+1,posand);

        return variable;
      }else{
        return undefined;
      }
    }else{
      return false;
    }
  }else{
    if(ruta.length === 0){
      return false;
    }else{
      return true;
    }
  }
}