Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript splits the string


May 09, 2021 CoffeeScript


Table of contents


Split the string

Problem

You want to split a string.

Solution

Use the split() method of the JavaScript string:

"foo bar baz".split " "
# => [ 'foo', 'bar', 'baz' ]

Discuss

String's split() approach is the standard JavaScript method. C an be used to split strings based on any separator, including regular expressions. This method can also accept a second argument that specifies the number of substrings returned.

"foo-bar-baz".split "-"
# => [ 'foo', 'bar', 'baz' ]
"foo   bar  \t baz".split /\s+/
# => [ 'foo', 'bar', 'baz' ]
"the sun goes down and I sit on the old broken-down river pier".split " ", 2
# => [ 'the', 'sun' ]