如何提取Fetch返回HTML文本中id=后至双引号前的所有字符串数组?
Hey there! Let's get this sorted out for you.
Your current code has two main issues that are keeping it from working:
indexOf()only finds the first occurrence of a substring, so you can't grab all the IDs this way.- There's a typo: you wrote
fullstringinstead offullString(JavaScript is case-sensitive!), which would throw an error.
To extract all IDs that follow the id="..." pattern, regular expressions are the way to go—they're designed for this kind of global pattern matching. Here are two solid solutions:
Solution 1: Using exec() with a loop (works in all modern browsers)
This approach iterates through every match in your HTML string and collects the IDs into an array:
// Replace this with your actual fetched HTML content const fullString = '<div id="main-content"><section id="hero"><p id="tagline">Hello World</p></section>'; const idPattern = /id="([^"]+)"/g; const extractedIds = []; let currentMatch; // Loop through all matches until exec() returns null while ((currentMatch = idPattern.exec(fullString)) !== null) { // currentMatch[1] holds the text inside the quotes after id= extractedIds.push(currentMatch[1]); } console.log(extractedIds); // Output: ["main-content", "hero", "tagline"]
Solution 2: Using matchAll() (cleaner, ES6+)
If you're working in an environment that supports ES6+ (most modern browsers and Node.js), matchAll() makes this even more concise:
const fullString = '<div id="main-content"><section id="hero"><p id="tagline">Hello World</p></section>'; const extractedIds = [...fullString.matchAll(/id="([^"]+)"/g)].map(match => match[1]); console.log(extractedIds); // Same output as above
A quick breakdown of the regex /id="([^"]+)"/g:
id=": Matches the literal textid="([^"]+): A capture group that grabs one or more characters that aren't a double quote (this ensures we only get the text inside the quotes)/g: The "global" flag, which tells the regex to find all matches instead of just the first one
That should do the trick—you'll have all your IDs neatly stored in an array!
内容的提问来源于stack exchange,提问作者Reactor
相关产品推荐
相关产品推荐

