0

Lets say I've created some code where the user can keep adding numbers to a <ul> and next to each <li> is a delete button which can be used to remove said item off the list. The problem is for it to work each item on the list does not only contain a number it also contains some text. Lets just say:

<li>Bag of potatoes - 25kg</li>

is there any way that I can use .innerText on this list item, to then just extract the number 25 (or whatever number happens to be there) so that I can subtract it from the total.

I have tried the following:

const itemText = item.parentElement.innerText;
const itemWeight = itemText.match(/\d/g) || [];

However in this example it returns 2,5 rather than 25. Is there a simple way I can convert the result 2,5 to 25, or is it possible to do this in a more efficient manner?

Thanks

Laurens
  • 3
  • 1

1 Answers1

0

as @Zsolt mentions in the comments you should add \d+ where the + means matches the previous match (the \d one) one and unlimited time. so you will get all the numbers in the text.

const itemWeight = itemText.match(/\d+/g) || [];

I really encourage you to play around with this website regex101 it is designed to help you understand the regular expression and test them so on...

I hope that solves your problem. Thanks

Hassan
  • 66
  • 4