get querystring using javascript and regex

2019-07-10 03:06发布

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>

3条回答
别忘想泡老子
2楼-- · 2019-07-10 03:32

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>
查看更多
成全新的幸福
3楼-- · 2019-07-10 03:38

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/

查看更多
祖国的老花朵
4楼-- · 2019-07-10 03:57

This should work:

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

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

查看更多
登录 后发表回答