Javascript’s Unicode Problem

A while ago I needed a simple string pad function, and since it’s a freakishly simple task, I just wrote a simple
function:

function limit(str, limit = 16, padString = "#", padPosition = "right") {
    const strLength = str.length;

    if (strLength > limit) {
        return str.substring(0, limit);
    } else if (strLength < limit) {
        const padRepeats = padString.repeat(limit - strLength);
        return (padPosition === "left") ? padRepeats + str : str + padRepeats;
    }
    return str;
}

Pretty simple, right? And it works too… Until you add in an emoji to your text. Then everything falls apart and worlds
collide! How? Simple:

"💩".length // 2!

(If you’re reading this on Linux you might actually see 2 broken unicode characters, and the result makes sense unless you have installed an emoji package on your browser or OS)...

Subscribe to my monthly newsletter

No spam, no sharing to third party. Only you and me.