Fred J. Fred J. - 11 months ago 65
Javascript Question

String replace regex character classes using regex

This string has regex character classes which need to be removed. As well as reduce multiple spaces to single space.

I can chain

but thought to ask if one can suggest a one regex code to do the whole job at one go. How can it be done? Thanks

"\n\t\t\t \n\n\t \n\t \t\tFood and drinks \n \t\n"

This is needed:

"Food and drinks"

var newStr = oldStr.replace(/[\t\n ]+/g, ''); //<-- failed to do the job

Answer Source

You want to remove all leading and trailing whitespace (space, tab, newline) but leave the spaces in the internal string. You can use the whitespace character class \s as shorthand, and match either the start or the end of the string.

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood and drinks \n \t\n";

// ^\s+ => match one or more whitespace characters at the start of the string
// \s+$ => match one or more whitespace characters at the end of the string
// | => match either of these subpatterns
// /g => global i.e every match (at the start *and* at the end)

var newStr = oldStr.replace(/^\s+|\s$/g/, '');

If you also want to reduce the internal spaces to a single space, I would recommend using two regexes and chaining them:

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood   and      drinks \n \t\n";
var newStr = oldStr.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' ');

After the first .replace() all of the leading and trailing whitespace is removed, leaving only the internal spaces. Replace runs of one or more space/tab/newline with a single space.

One other way to go could be to reduce all runs of whitespace to a single space, then trim the one remaining leading and trailing space:

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood   and      drinks \n \t\n";

var newStr = oldStr.replace(/\s+/g, ' ').trim();
// or reversed
var newStr = oldStr.trim().replace(/\s+/g, ' ');

.trim() doesn't exist prior to ES5.1 (ECMA-262) but the polyfill is essentially .replace(/^\s+|\s+$/g, '') (with a couple of other characters added) anyway.