E. Soomro E. Soomro - 1 year ago 116
HTML Question

Use Regex to get string from HTML tag attribute - JavaScript

I am very new to Regex but I think it is the best way to do this. I really need to get the text from an HTML tag attribute to an array of strings to be able to work with. I have multiple tags with an onclick attribute. It's the text from within the attribute that I need. I will give you an example.

<span class="ord" onclick="top.wiki_ord_klick('abstrakt','icke konkret, ogripbar')">abstrakt</span><br>

This is a span class with an onclick attribute. What I want to access is the words in top.wiki_ord_klick(...). I want them to be individually made strings and put into an array. The result would be

var result = ["abstrakt", "icke konkret, ogripbar"];

How can I do this?

Any help is appreciated.

Answer Source

The following uses match() with regular expression /'.+?'/. This matches everything between single quotes (including the quotes), and this returns the parameters as an array.

It then iterates through the array using map() to remove the single quotes.

var span = document.querySelector('span.ord'),  //get the <span> element
    click = span.onclick.toString(),            //get its inline click event as a string
    parms = click.match(/'.+?'/g);              //get an array of the onclick parameters

parms = parms.map(function(parm) {
  return parm.replace(/'/g, '');                //remove single quotes

<span class="ord" onclick="top.wiki_ord_klick('abstrakt', 'icke konkret', 'ogripbar')">abstrakt</span>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download