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)
JS.info ⟩ iterables
MasteringJS ⟩ JavaScript substring() vs slice()
String.prototype.slice() - returns new (sub)string.
String.prototype.substring() - returns new (sub)string.
String.prototype.substr() - depreacate.
iterator for String works correctly with surrogate pairs.
str.splice()
str.words() - of words in a sentence.
What is the difference between String.slice and String.substring?
Last updated 1 year ago