JavaScript Regular Expression Matching

Consider the following:

var params = location.search.match(/=([\w\d-]+)&?/g);
console.log(params);

Conclusion:

["=7&", "=31500&", "=1"]

I have no signs there, numbers or words, so I set the parentheses, but this does not work. So how do I do this?

+3
source share
3 answers

Are you getting the querystring parameter? I think this is what you want (although it does not use regex).

<script type="text/javascript">
<!--
function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

var koko = querySt("koko");

document.write(koko);
document.write("<br>");
document.write(hu);
-->
</script>

Link: http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml

+3
source

There is a nice javascript function called gup () that makes this thing simple. Here's the function:

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

and sample use:

var myVar = gup('myVar');

, :? myVar = asdf

myVar 'asdf'.

+2

.match , , .

, .exec :

var search = location.search, 
    param = /=([\w\d-]+)&?/g, 
    params = [],
    match;
while ((match = param.exec(search)) != null) {
    params.push(match[1]);
}
console.log(params);

, g . , .exec param, lastIndex , , , .exec . 0, . , 1 .

+2
source

All Articles