admin管理员组

文章数量:1318325

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

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

How do I get this, and display it in an input?

Thank you in advance.

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

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

How do I get this, and display it in an input?

Thank you in advance.

Share Improve this question edited May 17, 2011 at 21:31 user142162 asked May 17, 2011 at 21:27 curly_bracketscurly_brackets 5,59815 gold badges62 silver badges103 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

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

Take luck!

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

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

If it is just one key=value in the url you can use simple regex like this:

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

And set the value of an input like this

$('input').val(theValueYouWant)

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

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

Regex solution:

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

If multiple values are given for "keyword" (e.x. ?keyword=XXX&keyword=YYY), the regex will only find the first of these values (e.x. XXX). This regex works even if there are other variables in the query string.

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>

本文标签: javascriptExtract word from UrlStack Overflow