Regex to extract substring, returning 2 results for some reason

Rick picture Rick · Aug 15, 2010 · Viewed 169.2k times · Source

I need to do a lot of regex things in javascript but am having some issues with the syntax and I can't seem to find a definitive resource on this.. for some reason when I do:

var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test)

it shows

"afskfsd33j, fskfsd33"

I'm not sure why its giving this output of original and the matched string, I am wondering how I can get it to just give the match (essentially extracting the part I want from the original string)

Thanks for any advice

Answer

Jacob Relkin picture Jacob Relkin · Aug 15, 2010

match returns an array.

The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:

var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);