Skip to content Skip to sidebar Skip to footer

Javascript Unicode's Length (astral Symbols)

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 is that the Unicode special character

Solution 1:

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:

functioncountSymbols(string) {
    var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
    returnstring// 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('🏃2🔥7') returns 4

Here you have a small example: https://jsfiddle.net/q7g9qtk7/

Update: You can also use Array.from (polyfilling for IE, Chrome and Firefox already support it), which takes a string and splits it into each character, no matter how long it is:

Array.from('🏃2🔥7') //returns ["🏃", "2", "🔥", "7"]

So your function could be

functioncountSymbols(string) {
       returnArray.from(string).length;
}

Post a Comment for "Javascript Unicode's Length (astral Symbols)"