JavaScript Unicode's length (astral symbols)

后端 未结 1 1581
逝去的感伤
逝去的感伤 2021-01-22 05:23

I have a < input type=\"text\" > (in HTML) and everytime I add a character I do a if text.length < x {...} (in JavaScript).

The problem i

1条回答
  •  春和景丽
    2021-01-22 05:41

    I think you have most of the research done, you only need to put all of it together:

    Taking the function that your link provides:

    function countSymbols(string) {
        var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
        return string
            // Replace every surrogate pair with a BMP symbol.
            .replace(regexAstralSymbols, '_')
            // …and *then* get the length.
            .length;
    }
    

    your if should be

    if (countSymbols(document.getElementById("1").value)<16) { ...}
    

    For example: countSymbols('

    0 讨论(0)
提交回复
热议问题