JAVASCRIPT

Extract Specific Data Attributes from HTML Strings

Use regex to efficiently extract values from specific `data-*` attributes within an HTML string, useful for custom templating or parsing.

function extractDataAttribute(htmlString, attributeName) {
  // Create a regex dynamically to match data-<attributeName>="value"
  const regex = new RegExp(`data-${attributeName}="([^"]*)"`, 'g');
  const matches = [];
  let match;
  // Use exec in a loop to find all occurrences
  while ((match = regex.exec(htmlString)) !== null) {
    matches.push(match[1]); // The captured group [1] contains the attribute value
  }
  return matches;
}

// Example usage:
const html = '<div data-id="123" data-name="item1"></div><span data-id="456"></span><p data-action="click">Test</p>';
console.log(extractDataAttribute(html, 'id'));    // ["123", "456"]
console.log(extractDataAttribute(html, 'name'));  // ["item1"]
console.log(extractDataAttribute(html, 'action')); // ["click"]
How it works: This JavaScript function demonstrates how to extract values from specific `data-*` attributes within an HTML string using a dynamically created regular expression. It constructs a regex pattern like `data-id="([^"]*)"` to target a particular attribute. The `exec()` method is then used in a loop with the 'g' (global) flag to find all matches, capturing the value within the double quotes. This is useful for parsing custom data embedded in HTML, which can be applied in front-end templating or data scraping scenarios.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs