Search code examples
javascriptjqueryunicodeascii

JavaScript unicode aware string slice


I am trying to slice the string containing Unicode characters. but it returns a replacement character. here is my sample code.

let str = '𝒽𝑒𝓁𝓁𝑜 𝓌𝑜𝓇𝓁𝒹';
str = str.slice(0, -1); 
console.log(str);

which gives me below result

"𝒽𝑒𝓁𝓁𝑜 𝓌𝑜𝓇𝓁�"

how can I get rid of the replacement character?


Solution

  • Try this, it won't break a 4 byte character into 2:

    let str = '𝒽𝑒𝓁𝓁𝑜 𝓌𝑜𝓇𝓁𝒹';
    str = [...str].slice(0, -1).join(''); 
    console.log(str);