💾str.slice2()
JS ⟩ primitives ⟩ String ⟩ methods ⟩ .slice2()
returns new substring (Unicode supported)
💾 replit:str.slice2()
// 🔸 str.slice2()
// ⭐ supports surrogate pairs
String.prototype.slice2 = function(start, end) {
return Array.from(this) // ⭐ Array.from(string) works fine with unicode.
.slice(start, end)
.join('');
};
💈範例:
let str = '𝒳😂𩷶';
str.slice2(1, 3), // ✅ '😂𩷶'
// ⛔ native methods doesn't support surrogate pairs❗
str.slice(1, 3), // ❌ �� (garbage)
str.substring(1, 3), // ❌ �� (garbage)
Last updated
Was this helpful?