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.' |
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.
Good point, thanks.
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′);