0

I need to multiply HTML values which contains two numbers like the following:

<span class="elementClass">firstNumber / secondNumber</span>
<!-- for example -->
<span class="elementClass">2000 / 4000</span>

How do I get each number separately and multiply it for example by 2 and get value '4000 / 8000'.

Maybe something like this:

let m = $('.elementClass')[0].innerHTML;
$('.elementClass')[0].innerHTML = m * 2;
hayate
  • 3
  • 2

4 Answers4

2

Once you've got the innerHTML you need to get those 2 values from there as you already wrote.

let first_number = 0, second_number = 0

let tmp = $('.elementClass')[0].innerHTML;

tmp = tmp.trim() // remove spaces from the innerHTML string.

Once we get the innerHTML without any spaces, we need to split it into 2 values as per their separator.

In the above example / is a separator and then we can write the codes like this :

let ary = tmp.split('/')

first_number = ary[0]

second_number = ary[1]

web-sudo
  • 701
  • 2
  • 13
2

You could use a regex to get all digits before and after SPACE / SPACE.

let numbers = document.querySelector('.elementClass').innerHTML.split(/(\d*) \/ (\d*)/);

console.log('First: ' + 2 * numbers[1]); // numbers[1] is 2000
console.log('Seccond: ' + 2 * numbers[2]); // numbers[2] is 4000
<span class="elementClass">2000 / 4000</span>

The regex explained:

(\d*) \/ (\d*)
  -- ----  --
  |   |     |_____ match all digits
  |   |
  |   |____________ match space / space
  |   
  |________________ match all digits 

Find more information and explanation about the regex here: https://regex101.com/r/GkbHPm/1

caramba
  • 21,963
  • 19
  • 86
  • 127
0
numbers = $('.elementClass')[0].innerHTML.split("/");
first = parseInt(numbers[0].replace(/ /g, ''));
second = parseInt(numbers[1].replace(/ /g, ''));

multiplier = 2;

first = first * multiplier;
second = second * multiplier;

$('.elementClass')[0].innerHTML = String(first) + ' / ' + String(second);
rzlvmp
  • 7,512
  • 5
  • 16
  • 45
0

In case there are other (or multiple operands), you could simply evaluate the expression found in the innerHTML. For example,

newValue = eval($('.elementClass')[0].innerHTML);
$('.elementClass')[0].innerHTML = newValue;

View the JSFiddle Demo here.

This example also uses eval(). You should read why this is potentially dangerous before using it.

jeffresc
  • 884
  • 6
  • 9