简体   繁体   中英

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 replace() 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

I'd recommend this pattern (assuming you want to keep \\n s or \\t s in your main string):

/^[\t\n ]+|[\t\n ]+$/g

If you don't want to keep them, you can use something like this:

/^[\t\n ]+|[\t\n]*|[\t\n ]+$/g

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM