0

I have a block of html code that looks like this.

<ul class = "barcharts">
            <li class = "wind_v">-100kW</li>
            <li class = "battery_v">+20kW</li>
            <li class = "wave_v">+20kW</li>
            <li class = "station_v">+20kW</li>
            <li class = "charge_v">+20kW</li>
            <li class = "solar_v">+20kW</li>
            <li class = "factory_v">+20kW</li>
            <li class = "shops_v">-20kW</li>
            <li class = "house_v">+20kW</li>
        </ul>

I want to get an array using match() that will have both the + and - characters in it, ie, in this situation:

array = '-','+','+','+','+','+','-','+';

How do I format match() to let me make a search with multiple parameters like this?

Strawhare
  • 486
  • 5
  • 19

1 Answers1

0

Don't parse HTML with regexps. Instead, work with the DOM. You'll be glad you did.

// Get the first character of the content of a DOM element.
function firstCharOfContent(elt) { return elt.textContent[0]; }

// Get the li elements.
// Fix this to pick out different sets of elements.
var lis = document.querySelectorAll('ul.barcharts li');

// Map that array into one containing the first characters of the content of each.
[].map.call(lis, firstCharOfContent)

If for some reason your heart is set on using match, then

ul.innerHTML.match(/[+-]/g) 

would do the job.

  • I have more than just this list on the webpage, would it not also catch the contents of all of them as well? – Strawhare Jul 20 '15 at 13:18
  • try this youtString.match(/(.)/g) – Raghavendra Jul 20 '15 at 13:18
  • @irishMTS Yes, it would. You would need to change the content of the `querySelector` call to pick out the ones you wanted, for instance `querySelector('ul.barcharts')`. –  Jul 20 '15 at 13:19
  • Great, I think that does the job then, Thanks! One question though, why the opposition to parsing HTML with regexps? When might this be a bad idea? – Strawhare Jul 20 '15 at 13:28
  • you can directly use like this yourString.match(/[+-]/g) – Raghavendra Jul 20 '15 at 13:30
  • See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454. –  Jul 20 '15 at 13:58