hayate
hayate

Reputation: 3

Multiply in Jquery

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;

Upvotes: 0

Views: 76

Answers (4)

caramba
caramba

Reputation: 22480

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

Upvotes: 2

rzlvmp
rzlvmp

Reputation: 9364

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

Upvotes: 0

jeffresc
jeffresc

Reputation: 894

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.

Upvotes: 0

web-sudo
web-sudo

Reputation: 686

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]

Upvotes: 2

Related Questions