Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert part of string of text to fractions

I have a string which is a product name and product size:

(source: https://www.bagnboxman.co.uk/product/0215-e-flute-carton-180-x-150-x-370mm-with-50mm-dia-hole/)

Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)

And I want to convert it to this:

Corrugated Box
7⅛ x 5⅞ x 14½" (180 x 150 x 370mm)

I have put the # sign in for ease of use, so I can search for the # and convert it to a line-break (br).

I then also want to look for the inch fractions and convert them to the appropriate..

½

..code.

How would I go about doing this? I have google extensively this morning and tried a few things but just can't figure this out. I only have basic JS knowledge I'm afraid.

like image 820
tjcss Avatar asked Sep 01 '17 08:09

tjcss


1 Answers

You could search for space, the number, slash and another number and return the wanted format.

var string = 'Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)'

string = string.replace(/\s(\d)\/(\d)/g, '&frac$1$2;').replace('#', '<br>');

document.body.innerHTML += string;

For changing all divs of the class product-name, you could iterate the elements.

document.body.onload = function () {
    Array.prototype.forEach.call(document.getElementsByClassName('product-name'), function (element) {
        element.innerHTML = element.innerHTML.replace(/\s(\d)\/(\d)/g, '&frac$1$2;').replace('#', '<br>');
    });
}
<div class="product-name">Corrugated Box # 7 1/8 x 5 7/8 x 14 1/2" (180 x 150 x 370mm)</div>
like image 190
Nina Scholz Avatar answered Oct 05 '22 18:10

Nina Scholz