Skip to content

Commit db17fc3

Browse files
committed
Use polyfill for String::trim instead of global function declaration
1 parent 7f951c9 commit db17fc3

File tree

1 file changed

+3
-4
lines changed

1 file changed

+3
-4
lines changed

chapters/strings/trimming-whitespace-from-a-string.md

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,12 @@ To trim only trailing whitespace, use the following:
3434

3535
## Discussion
3636

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:
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, otherwise create a polyfill:
3838

3939
{% highlight coffeescript %}
40-
trim = (val) ->
41-
if String::trim? then val.trim() else val.replace /^\s+|\s+$/g, ""
40+
if !String::trim? then String::trim = -> @replace /^\s+|\s+$/g, ""
4241

43-
trim " padded string "
42+
" padded string ".trim
4443
# => 'padded string'
4544
{% endhighlight %}
4645

0 commit comments

Comments
 (0)