JavaScript Get real length of a string (without entities)

前端 未结 5 551
别跟我提以往
别跟我提以往 2021-02-05 10:27

I need to determine the length of string which may contain html-entities.

For example \"&darr ;\" (↓) would return length 6, which is correct, but I want these

5条回答
  •  悲&欢浪女
    2021-02-05 10:59

    alert(document.getElementById("foo").innerHTML.length); // alerts 1

    So based on that rationale, create a div, append your mixed up entity ridden string to it, extract the HTML and check the length.

    var div = document.createElement("div");
    div.innerHTML = "↓↓↓↓";
    alert(div.innerHTML.length); // alerts 4
    

    Try it here.

    You might want to put that in a function for convenience, e.g.:

    function realLength(str) { // maybe there's a better name?
        var el = document.createElement("div");
        el.innerHTML = str;
        return el.innerHTML.length;   
    }
    

提交回复
热议问题