Search code examples
javascripthtmllabel

How would I be able to extract the words in my label, including the space in between words but not any additional spaces afterwards?


I'm currently lost as to how I would be able to properly use the label in my HTML as variables for my JS.

[HTML]
<div> <!--Main Toppings-->
  <label for = "mtop"> Main Toppings: </label>
  <select name="mainToppings" id = "toppingsoption" required>
  <option disabled selected id = 'emptyoption'> -- select an option -- </option>
  <option id='pepperoniOverload' class = "mtopchoice">Pepperoni Overload - &#8369 100</option>
  <option id='hawaiian' class = "mtopchoice">Hawaiian - &#8369 50</option>
  <option id='meatOverload' class = "mtopchoice">Meat Overload - &#8369 125</option>
  </select>
</div>

[JavaScript]
var toppings = document.getElementById("toppingsoption");
    if (toppings.options[toppings.selectedIndex].id == 'emptyoption') {
        var toppingsName = '';
        var toppingsValue = 0;
    } else {
        var toppingsText = toppings.options[toppings.selectedIndex].innerHTML;
        var toppingsName = toppingsText.replace(/[^a-z]/gi, '');
        var toppingsValue = parseInt(toppingsText.replace(/\D/g,''));
    
        console.log(toppingsName, toppingsValue, "getMainToppings() working");
    }

While the current code works just fine for dealing with the 'Hawaiian' option, 'Pepperoni Overload' and 'Meat Overload' is messing with the way I extract the text out of the labels. What would be the correct way so that I would be able to extract the words Pepperoni Overload and Meat Overload, maintaining the space between words but not extracting the additional spaces that follow afterwards?


Solution

  • Just extract everything until the - symbol. Something like the following should work:

    /(.*)-/g
    

    And then you could just extract the first group and should get what you want.