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 Replies 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’);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: