Amran Amran - 1 year ago 56
Javascript Question

What does [1] do on function?

I need an explanation on below js code,

function getURLParameter(url, name) {
return (RegExp(name + '=' + '(.+?)(&|$)')
.exec(url)||[,null])[1];
}

var id = getURLParameter(url, 'id');
console.log(id); //1

// let say the example of url is
// index.php?id=1&user=xxx


What is
[1]
on the return statement use for?

I am confuse on how does it get the value of 1 for the id

Answer Source

RegExp.prototype.exec() returns an array including the matches of the regular expression (or null).

[1] just accesses the second element in that array — in this case the value of the capturing group in the regular expression.

It's equivalent to:

function getURLParameter(url, name) {
  var regexp = new RegExp(name + '=' + '(.+?)(&|$)');
  var result = regexp.exec(url); // array containing the full string of 
                                 // characters matched, the value of the
                                 // capturing group and the end anchor
                                 // (or null)
  if (Array.isArray(result)) {
    return result[1];
  } else {
    return null;
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download