medev21 medev21 - 11 days ago 7
Javascript Question

grab number from an array of string - regex - javascript

I have an array of strings; they are URLs. I would like to grab a specific number from each URL.

These urls are in this format:

"http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk"


I would like to grab the fifth digit code after
banner?l_id
, which is
111111
. Keep in mind the fifth digit code and the other ones can be any random number, it's not always zeros or ones.

Array sample:

["http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
"http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
"http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
"http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
"http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk"
]


Like I said, I have an array of url strings and trying to figure it out how to grab the fifth digit code using Javascript; regex could help me achieve this but I'm not familiar w/ regex.

I was told python could be easier to solve this, but I'm building a chrome ext. which is using JS.

Thanks for your help in advance!

Answer

You could do it without Regex with just split() chained with apropriate index choice :

var addresses = ["http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
 "http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
 "http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
 "http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk",
 "http://display.companyX.com/rest/banner?l_id=A000-0000-0000000-000000-111111-0-0-0&k=A77K_fakfhaskfhkjshfkjo=kafkjafk"
 ];
var results = addresses.map(x => x.split("?")[1].split("&")[0].split("-")[4])
console.log(results);

Comments