-4

For example,I have an input of "cid=5",and the output of this function is an array({cid=5,,5}).I'm confused about the result.Could someone help me to explain this question?

    function getParameter(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
        var r = location.search.substr(1).match(reg);
        if (r!=null) return (r[2]); return null;
}

Thanks for the comment below,but I still confused about this question.So,I will try to express my question more clearly. The second parameter of the RegExp object is 'i',that means ignore case and it will match once and return a String object.So why it return a String array like{cid=5,,5,}?

JHChoi
  • 1
  • 1
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match – Poul Bak Dec 07 '20 at 02:59
  • Does this answer your question? [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – 41686d6564 Dec 07 '20 at 03:05
  • You can breakdown your problem so you can ask a more clear question: Currently, I'm not sure you're trying to regex pattern or the rest of your function? If you wanna understand that regex pattern, please use https://regex101.com/ and see the Explaination box – Neo.Mxn0 Dec 07 '20 at 03:44

1 Answers1

0

The second parameter of the RegExp object is 'i',that means ignore case and it will match once and return a String object.So why it return a String array like{cid=5,,5,}?

The regular expression being used in this case includes capturing groups. If the 'g' flag isn't set, the array returned from String.match includes the complete match and its related capturing groups.

(^|&) creates a capturing group of start of string or ampersand

([^&]*) creates a capturing group of any character that isn't an ampersand zero to many times

(&|$) creates a capturing group of an ampersand or end of string

Amy Shackles
  • 124
  • 1
  • 5
  • I know what the RegExp means,I don't know why it returns a array and the result is {cid=5,,5,}. – JHChoi Dec 07 '20 at 07:05