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

CoffeeScript cleans up the blanks before and after the string


May 09, 2021 CoffeeScript


Table of contents


Cleans up the blanks before and after the string

Problem

You want to clean up the blanks before and after the string.

Solution

Replace the blank character with JavaScript's regular expression.

To clean up the blanks before and after the string, you can use the following code:

"  padded string  ".replace /^\s+|\s+$/g, ""
# => 'padded string'

If you only want to clean up the blank characters in front of the string, use the following code:

"  padded string  ".replace /^\s+/g, ""
# => 'padded string  '

If you only want to clean up the blanks behind the string, use the following code:

"  padded string  ".replace /\s+$/g, ""
# => '  padded string'

Discuss

Prototypes of String in Opera, Firefox, and Chrome all have native trim methods, and other browsers can add one. For this method, use the built-in method as much as possible, otherwise create a polyfill:

unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, ""

"  padded string  ".trim()
# => 'padded string'

Grammar blocks

You can also add syntax blocks similar to those in Ruby that define the following shortcuts:

String::strip = -> if String::trim? then @trim() else @replace /^\s+|\s+$/g, ""
String::lstrip = -> @replace /^\s+/g, ""
String::rstrip = -> @replace /\s+$/g, ""

"  padded string  ".strip()
# => 'padded string'
"  padded string  ".lstrip()
# => 'padded string  '
"  padded string  ".rstrip()
# => '  padded string'

To learn more about JavaScript's performance when performing trim operations, see Steve Levithan's blog post.