To split a string in JavaScript, you can use the split()
method. The split()
method splits a string into an array of substrings and returns the new array.
const str = `This is an example string`
const tokens = str.split(' ')
console.log(tokens)
// [ 'This', 'is', 'an', 'example', 'string' ]
If an empty string (''
) is passed as the separator, the string is split between each character.
const str = `Hello world!`
const tokens = str.split('')
console.log(tokens)
// ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
Note that the split()
method does not change the original string.