get querystring using javascript and regex

纵然是瞬间 提交于 2019-12-11 01:36:35

问题


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>


来源:https://stackoverflow.com/questions/9449921/get-querystring-using-javascript-and-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!