DEV Community

Discussion on: Gotchas when converting strings to arrays in JS

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

This is a little obscure and not Unicode-related, so I'm leaving it outside the main article, but we can even create a custom class that inherits from String but with different iteration behavior, by overriding its Symbol.iterator method:

class WeirdString extends String {
    isWeird = true

    ;*[Symbol.iterator]() {
        yield* this.split('_')
    }
}

const weirdStr = new WeirdString('aaa_b')
Enter fullscreen mode Exit fullscreen mode

Here, we can see clearly the different behaviors at work:

weirdStr.split('') // ["a", "a", "a", "_", "b"]

;[...weirdStr] // ["aaa", "b"]

Array.from(weirdStr) // ["aaa", "b"]

Object.assign([], weirdStr) // ["a", "a", "a", "_", "b", isWeird: true]
Enter fullscreen mode Exit fullscreen mode

We also see that the isWeird property is preserved when using Object.assign, because it's an enumerable own property.