I have this HTML table: https://jsfiddle.net/wt8dnkor/
What I try to do is to loop over all elements - all table cell, find if there is string 'cm' and if yes then to convert a value from cm to inches.
So I write this code:
var allDivTd = document.getElementById("sizeadviser_content").getElementsByTagName("TD");
for(var i = 0; i < allDivTd.length; i++){
var td = allDivTd[i];
if (td.innerText.includes("cm") === true) {
//td.innerText = td.innerText+' in';
}
}
So as you can see I want to change only cells where the string contains 'cm'.
How to get number values from the cell and convert them to inches using 1 decimal?
The problem is because I dont know how many number values are in cell. They could be in format like 20cm or 20-50cm or 20 - 50 cm or 20 | 50 cm
20cm or 20-50cm or 20 - 50 cm or 20 | 50 cm
... etc.
If you need a very fast solution, you can use something like this
function setStr(str) {
let digit = '';
let newStr = '';
for (let char of str) {
if (!isNaN(char)) {
digit += char;
} else {
newStr += converter(digit)+ char;
digit = '';
}
}
return newStr.replace('cm', 'in');
}
function converter(s) {
if (s) {
return (parseInt(s)*0.393707).toString();
}
return '';
}
or using regex
function parseString(str) {
var matcher = /\D+/;
var list = str.split(matcher);
list.forEach((item) => {
if (item) {
str = str.replace(item, (parseInt(item)*0.393707).toString());
}
});
return str.replace('cm', 'in');
}
i think u could use the regx by using split(/\D+/)
check my example
function gtnmbrs () { var strng = '50 - 10 | 555 cm'; var nonnmbrs = /\D+/; var rslt = strng.split(nonnmbrs); for (i=0; i<rslt.length; i++) { document.write("<p>"+rslt[i]*0.39370+" inch</p>"); } }
<p>Convert to:</p> <input type="button" id="bt" value="Click it!" onclick="gtnmbrs()"/>
check out this snippet it could help u to get out the numbers only, then convert it from cm to inch
Here's a version that should work for decimal values:
for (var i = 0; i < allDivTd.length; i++) {
var td = allDivTd[i];
if (td.innerText.includes("cm") === true) {
new_td = td.innerText.replace('cm', '').replaceAll(' ', '');
for (let char of new_td) {
if (isNaN(char) && char != ".") {
new_td = new_td.replace(char, ",").split(',');
new_td.forEach(function(centim, index, myArray) {
myArray[index] = (centim * 0.393701).toFixed(2);
});
new_td = new_td.toString().replace(',', ' - ') + ' in'
td.innerText = new_td;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.