JavaScript regular expression behaviour

17 hours ago 1
ARTICLE AD BOX

I have next JavaScript code in a HTML document.

var a="abc=def&ghi=jkl&mno=pqr".split(/(^|&).*?(=|$)/); alert("0='"+a[0]+"' 1='"+a[1]+"' 2='"+a[2]+"' 3='"+a[3]+"' 4='"+a[4]+"' 5='"+a[5]+"' 6='"+a[6]+"' 7='"+a[7]+"' 8='"+a[8]+"' 9='"+a[9]+"' a='"+a+"'")

Expected output is as follows.

0=`def` 1=`jkl` 2=`pqr` 3=`undefined` 4=`undefined` 5=`undefined` 6=`undefined` 7=`undefined` 8=`undefined` 9=`undefined` a=`def,jkl,pqr`

But instead of it I get the following.

0=`` 1=`` 2=`=` 3=`def` 4=`&` 5=`=` 6=`jkl` 7=`&` 8=`=` 9=`pqr` a=`,,=,def,&,=,jkl,&,=,pqr` Why are the = and & substrings not matched as the splitter part, and therefore fall to the array? Why are there two empty substrings at the array beginning? How can I get the expected output?

jsotola's user avatar

jsotola

2,2551 gold badge16 silver badges32 bronze badges

green's user avatar

4

Read Entire Article