0

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 <span> 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?

1
  • 1
    Sorry for the inconvenience! I ment it like two strings, icke konkret and ogripbar should be only one string. I'll update the question. Commented Nov 14, 2016 at 19:08

1 Answer 1

2

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
});

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.