-1

I need to iterate over an array of html and return the ID, for example ['<div id="menu"></div>'] needs to return 'menu', ['<div id="online-menu">A La Carte</div>', '<div id="red-box">Welcome to the site</div>','<div id="hello">Hello</div>'] would return ['online-menu', 'red-box', 'hello']

my code so far is:

const getID = divs => {

const regex = /"[^"]*"/g

let returnedString = ''
while(returnedString = regex.exec(divs))


return returnedString

So I'm currently getting the following error:

AssertionError: expected [ Array(1) ] to deeply equal [ 'online-menu' ]
+ expected - actual

[
- "\"online-menu\""
+ "online-menu"
]

Is anyone able to give me a nudge in the right direction, I have already tried .slice(1, -1) which gave me an empty array if used before the return statement and null when used within the return statement

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
newtojs
  • 31
  • 3

1 Answers1

2

your regex is formed in such a way that you SHOULD expect quotes in the result. you are asking the regex parser to look for a string that starts with a quote, with any character other than a quote, that ends in a quote. That spec, matches perfectly with what you are getting back.

You should utilize regex groups to separate your concerns. What you want to do is match the quoted string, but target only the text inside it.

const getID = divs => {
//lets assume that divs is a single string
const regex = /"([^"]*)"/

let matched = divs.match(regex);
let returnedString = matched[1];
return returnedString;
}

if divs is supposed to be an array of html strings, then just pop this function into an array map. Or iterate through them inside the function using the same logic.

Also, if you specifically want ID's you should consider that all html attributes come in the form of the regex you provided, which would mean that since you are doing a global match, you will be returned all of them.

you should think about specifically targeting ids like regex = /id="([^"]*)"/

Ja Superior
  • 459
  • 4
  • 17