-4

I am attempting to use regular expressions to pull out something similar to the below string. However, there will be multiple with different functions within the data-plugin attribute.

<div class="plugin" data-plugin="function(1,2,'func')"></div>

I was using an expression like the following:

/<div class="js-plugin" data-plugin="([a-zA-Z0-9\(\),\' ]*)"></div>/

However, this can't work as the string like 'func' could include all sorts of special characters.

How can I use a regular expression to pull out the entire string, and match the contents within data-plugin="" as well as presuming there may be multiple matches.

mdixon18
  • 1,199
  • 4
  • 14
  • 35
  • Why do you want to use regular expressions for this?? – UnholySheep Jan 31 '17 at 15:15
  • 4
    You will definitely want to read : [You can't parse HTML with regex](http://stackoverflow.com/a/1732454/1175966) – charlietfl Jan 31 '17 at 15:16
  • Well, i've landed on some code im having to work on. It uses PHP, now im having to use regex to go through a massive HTML string and take out these functions so i can eval() them and the HTML replaces it and outputs to the page essentially. – mdixon18 Jan 31 '17 at 15:17

2 Answers2

4

Don't use regex to get data from a html element. Select the element and use dom methods to get the data instead.

console.log(document.querySelector(".plugin").getAttribute("data-plugin"));
<div class="plugin" data-plugin="function(1,2,'func')"></div>
baao
  • 71,625
  • 17
  • 143
  • 203
0

If you need regex, this should work.

Regex:

\bdata-plugin="([a-zA-Z0-9\(\),\']*)

Input:

<div class="plugin" data-plugin="function(1,2,'func')"></div>

Output:

function(1,2,'func')

const regex = /\bdata-plugin="([a-zA-Z0-9\(\),\']*)/;
const str = `<div class="plugin" data-plugin="function(1,2,'func')"></div>
`;
let m;

if ((m = regex.exec(str)) !== null) {
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

See: https://regex101.com/r/FPH9O3/3

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See [answer] for more information. – Heretic Monkey Jan 31 '17 at 17:53