get querystring using javascript and regex

2019-07-10 03:16发布

问题:

I will have my url as this:

http://mysite.com/results.aspx?s=bcs&k="Hospital" OR "Office" OR "Facility"

I want to grab everything after 'k=', excluding 'k=' itself..

And this regex is partially working..but it grabs everything with k two times..

    <script type="text/javascript">
document.write('<p>Showing Results for all' + 
window.location.href.match(/[?&]k=([^&#]+)/) || [] + '</p>');
</script>

回答1:

match is returning two elements. The first is a match of the entire regex. The 2nd element is the capturing group (what is within the ()). This is what you want, the 2nd element in the array.

<script type="text/javascript">
    var result = window.location.href.match(/[?&]k=([^&#]+)/);

    var word = "";

    if(result) word = result[1];
</script>

http://jsfiddle.net/7WcMc/



回答2:

This should work:

var match = location.href.match(/\&k\=(.+)/)[1];

http://jsfiddle.net/elclanrs/2aPCh/1/



回答3:

Javascript match function returns an array of matches in case of success or null if no match is found.

In your case first match is the whole string matched, second is backreference to ([^&#]+)

Probably better in this way:

<script type="text/javascript">
    var m = window.location.href.match(/[?&]k=([^&#]+)/);
    document.write('<p>Showing Results for all' + ((m != null) ? m[1] : '') ++ '</p>');
</script>