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.

> 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.'

5 responses to “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’);

  3. Why not just str.trim();?

    1. I think I was just a javascript noob.

Leave a reply to Corey Cancel reply