Advanced template string splitting

126 views Asked by At

I just found this really cool way to split a string, but I'm not sure why it works can anyone please explain it to me. .split`` instead of .split("")

let str = "Justin"
console.log(str.split``) 
// ["J", "u", "s", "t", "i", "n"]

2

There are 2 answers

0
Patrick Roberts On BEST ANSWER
let str = "Justin"
console.log(str.split``)

is a tagged template, which is equivalent to:

let str = "Justin"
const strings = Object.freeze(Object.assign([""], { raw: [""] }))
console.log(str.split(strings))

This works because String.prototype.split(separator[, limit]) will convert the separator to a string in ยง21.1.3.21 step 7 if it doesn't implement the Symbol.split method (checked in step 2), and [""].toString() === "".

0
xavc On

It's a result of tagged templates, str.split is treated as a tag of the template (``), and thus is called with the empty string as its first argument.