My name is  
Jurgens du Toit.
Systems Developer.
Problem Solver.

About Me

Technology and Solving Problems are my passion. I'm a South African that loves my wife, life, and coding.

I'm writing a book!

The Logstash Config Guide

Buy it now on Leanpub

18 July 2011

A JavaScript trim function

By Jurgens du Toit

A simple enough trim function for JavaScript:

function trim(string) {
    return string.replace(/^\s*|\s*$/g, '')
}

The regular expression translates as

  • ^ - At the beginning of the line
  • \s* - Take all the white space you can find, if there is any
  • | - OR
  • \s* - Take all the white space you can find, if there is any
  • $ - At the end of the line

The g parameter at the end ensures that all instances are replaced.

The replace function uses the regular expressions to replace the white space it found at the beginning or the end of the string with an empty string.

Easy enough!

blog comments powered by Disqus