4

I have the following:

$(document).ready(function() {
window.location.href='http://target.SchoolID/set?text=';
});

So if someone comes to a page with the above mentioned code using a url like:

Somepage.php?id=abc123

I want the text variable in the ready function to read: abc123

Any ideas?

jini
  • 10,875
  • 34
  • 97
  • 167

3 Answers3

4

you don't need jQuery. you can do this with plain JS

function getParameterByName( name ) //courtesy Artem
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

and then you can just get the querystring value like this:

alert(getParameterByName('text'));

also look here for other ways and plugins: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Moin Zaman
  • 24,919
  • 6
  • 67
  • 73
  • Added another answer. If you feel like it update your answer and i will delete mine. Thanks for the helpful code. – ojblass Jun 02 '15 at 19:49
3

check out the answer to this questions: How can I get query string values in JavaScript?

that'll give you the value of the id parameter from the query string.

then you can just do something like:

$(document).ready(function() {
    var theId = getParameterByName( id)
    var newPath = 'http://target.SchoolID/set?text=' + theId
    window.location.href=newPath;
});
Community
  • 1
  • 1
Patricia
  • 7,717
  • 3
  • 34
  • 70
0

To help people coming after me that want to have multiple variables and to enhance Moin's answer here is the code for multiple variables:

function getParameterByName( name ) //courtesy Artem
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
  {
    if ((results[1].indexOf('?'))>0)
        return decodeURIComponent(results[1].substring(0,results[1].indexOf('?')).replace(/\+/g, " "));
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}
ojblass
  • 20,489
  • 22
  • 79
  • 127