Skip to content

Commit 81bb6f9

Browse files
committed
add recipe for trimming whitespace from a string
1 parent 9f2c544 commit 81bb6f9

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
layout: recipe
3+
title: Trimming whitespace from a String
4+
chapter: Strings
5+
---
6+
## Problem
7+
8+
You want to trim whitespace from a string.
9+
10+
## Solution
11+
12+
Use JavaScript's Regular Expression support to replace whitespace.
13+
14+
To trim leading and trailing whitespace, use the following:
15+
16+
{% highlight coffeescript %}
17+
" padded string ".replace /^\s+|\s+$/g, ""
18+
# => 'padded string'
19+
{% endhighlight %}
20+
21+
To trim only leading whitespace, use the following:
22+
23+
{% highlight coffeescript %}
24+
" padded string ".replace /^\s+/g, ""
25+
# => 'padded string '
26+
{% endhighlight %}
27+
28+
To trim only trailing whitespace, use the following:
29+
30+
{% highlight coffeescript %}
31+
" padded string ".replace /\s+$/g, ""
32+
# => ' padded string'
33+
{% endhighlight %}
34+
35+
## Discussion
36+
37+
Opera, Firefox and Chrome all have a native string prototype `trim` method, and the other browsers could add one as well. For this particular method, I would use the built-in method where possible:
38+
39+
{% highlight coffeescript %}
40+
trim = (val) ->
41+
if String::trim? then val.trim() else val.replace /^\s+|\s+$/g, ""
42+
43+
trim " padded string "
44+
# => 'padded string'
45+
{% endhighlight %}
46+
47+
48+
### Syntax Sugar
49+
50+
You can add some Ruby-like syntax sugar with the following shortcuts:
51+
52+
{% highlight coffeescript %}
53+
String::strip = -> if String::trim? then @trim() else @replace /^\s+|\s+$/g, ""
54+
String::lstrip = -> @replace /^\s+/g, ""
55+
String::rstrip = -> @replace /\s+$/g, ""
56+
57+
" padded string ".strip()
58+
# => 'padded string'
59+
" padded string ".lstrip()
60+
# => 'padded string '
61+
" padded string ".rstrip()
62+
# => ' padded string'
63+
{% endhighlight %}
64+
65+
For an interesting discussion and benchmarks of JavaScript `trim` performance, see [this blog post][1] by Steve Levithan.
66+
67+
[1] http://blog.stevenlevithan.com/archives/faster-trim-javascript

wanted-recipes.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ In the notes below, "JS" means the recipe is just a simple passthrough to an exi
2020
* substr # str.substr(x,y) === str[x..x+y-1] === str[x...x+y]
2121
* substring # str.substring(x,y) === str.slice(x,y) === str[x..y-1] === str[x...y]
2222
* Replacing substrings
23-
* Trimming whitespace from the end of a string
2423

2524
## Arrays
2625

0 commit comments

Comments
 (0)