Skip to content

Commit ea1106f

Browse files
author
Dan Gilbert
committed
New recipe: splitting a string.
1 parent b4ce259 commit ea1106f

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
layout: recipe
3+
title: Splitting a String
4+
chapter: Strings
5+
---
6+
7+
h2. Problem
8+
9+
You want to split a string.
10+
11+
h2. Solution
12+
13+
Use JavaScript's String split() method:
14+
15+
{% highlight coffeescript %}
16+
"foo bar baz".split " "
17+
# => [ 'foo', 'bar', 'baz' ]
18+
{% endhighlight %}
19+
20+
h2. Discussion
21+
22+
String's split() is a standard JavaScript method. It can be used to split a string on any delimiter, including regular expressions. It also accepts a second parameter that specifies the number of splits to return.
23+
24+
{% highlight coffeescript %}
25+
"foo-bar-baz".split "-"
26+
# => [ 'foo', 'bar', 'baz' ]
27+
{% endhighlight %}
28+
29+
{% highlight coffeescript %}
30+
"foo bar \t baz".split /\s+/
31+
# => [ 'foo', 'bar', 'baz' ]
32+
{% endhighlight %}
33+
34+
{% highlight coffeescript %}
35+
"the sun goes down and I sit on the old broken-down river pier".split " ", 2
36+
# => [ 'the', 'sun' ]
37+
{% endhighlight %}

wanted-recipes.textile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ h2. Objects
1818
h2. Strings
1919

2020
* HTML methods # JS .sup(), .sub(), .blink(), .link(url), etc. May not exist in your JS impl!
21-
* Splitting a string # JS "foo bar baz".split ' ' # => [ 'foo', 'bar', 'baz' ]
2221
* substr # str.substr(x,y) === str[x..x+y-1] === str[x...x+y]
2322
* substring # str.substring(x,y) === str.slice(x,y) === str[x..y-1] === str[x...y]
2423
* Uppercasing a string # JS toUpperCase()

0 commit comments

Comments
 (0)