Extract word from Url

I have a search function and I would like to display the search query in the search input.

My url is: search-1.html?keyword=XXXXXX

How do I get this and display it in the input?

Thanks in advance.

+5
source share
4 answers

If this is just one key=valuein the url, you can use a simple regex:

var theValueYouWant = window.location.href.match(/keyword=(.+)/)[1]

And set the input value like this

$('input').val(theValueYouWant)

If you want to parse the GET string more carefully, this function should do it ...

gets = {};
$.each(location.search.replace(/^\?/,'').split('&'),function(k,v){
    bits = v.split('=');
    gets[bits[0]] = bits[1];
});
+2
source

Use this: http://ajaxcssblog.com/jquery/url-read-get-variables/

Good luck

Oh, and then you can use the following to display its value in the input field:

$("#inputId").val($.url.param("keyword"));
+3

:

var S = window.location.search; // "?keyword=..." etc.
var T = S.match(/^\?(?:[^\b]*&+)?keyword=([^&]*)/);
if (T)
   T = T[1]
else
   T = "no keywords found"

"keyword" (e.x. ?keyword=XXX&keyword=YYY) , (e.x. XXX). , .

+1
source

jQuery-less solution:

<script type="text/javascript">
var $_GET=[],pairs=location.href.toString().substring(location.href.toString().indexOf("?")+1).split("&");for(key in pairs){pos=pairs[key].indexOf("=");$_GET[pairs[key].substring(0,pos)]=decodeURIComponent(pairs[key].substring(pos+1).replace(/\+/g," "))};

// Now just access with $_GET
// example...
keyword = $_GET["keyword"];
</script>
0
source

All Articles