JavaScript regex for stripping leading & trailing whitespaces

I’m sure there are a bunch of libraries that do this, but sometimes wrestling with regexes is fun.

1
2
3
4
5
> var str = "           This string has some mighty fine whitespace.       ";
> str
'           This string has some mighty fine whitespace.       '
> str.replace(/^(\s*)((\S+\s*?)*)(\s*)$/,"$2");
'This string has some mighty fine whitespace.'

3 thoughts on “JavaScript regex for stripping leading & trailing whitespaces

  1. You should use non-capturing groups (?:) if you don't need to save matches, like so: replace(/^(?:s*)([Ss]*?)(?:s*)$/,"$1"); Right now each the first spacing, each letter, the striped string and the trailing white space all get put into their own capture groups.

  2. I don’t know why you would need the groups at all. Anyway your reg-exp is way too complicated for my taste. Here’s how I’d do the same thing:
    str.replace(/^\s*(.*?)\s*$/, ‘$1′);

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">