JSFiddle - React, Tailwind, and code Playground

by prozoroff

HTML

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<div id="123"></div>

JavaScript

function getStringWidthUsingSvg(string, fontFamily, fontWeight, fontStyle, fontSize) {
        var repeatNum = 100;
        var style = {
            fontFamily: fontFamily,
            fontWeight: fontWeight,
            fontSize: fontSize,
            fontStyle: fontStyle || "normal"
        };
        var el = document.createElementNS('http://www.w3.org/2000/svg', 'g');
        var ts = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
        ts.appendChild(document.createTextNode(string.repeat(repeatNum)));
        el.appendChild(ts);
        document.getElementById("123").appendChild(el);
        var domBBox = el.getBBox();
        alert(domBBox.width);
        $(el).remove();


        return (domBBox.width/repeatNum).toFixed(2);
    }
    
alert(getStringWidthUsingSvg("A", "Tahoma", "normal", "normal", "72px"));