|
| 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 |
0 commit comments