javascript - String replace regex character classes using regex -
this string has regex character classes need removed. reduce multiple spaces single space.
can chain replace()
thought ask if 1 can suggest 1 regex code whole job @ 1 go. how can done? thanks
"\n\t\t\t \n\n\t \n\t \t\tfood , drinks \n \t\n"
this needed:
"food , drinks"
var newstr = oldstr.replace(/[\t\n ]+/g, ''); //<-- failed job
you want remove leading , trailing whitespace (space, tab, newline) leave spaces in internal string. can use whitespace character class \s
shorthand, , match either start or end of string.
var oldstr = "\n\t\t\t \n\n\t \n\t \t\tfood , drinks \n \t\n"; // ^\s+ => match 1 or more whitespace characters @ start of string // \s+$ => match 1 or more whitespace characters @ end of string // | => match either of these subpatterns // /g => global i.e every match (at start *and* @ end) var newstr = oldstr.replace(/^\s+|\s$/g/, '');
if want reduce internal spaces single space, would recommend using 2 regexes , chaining them:
var oldstr = "\n\t\t\t \n\n\t \n\t \t\tfood , drinks \n \t\n"; var newstr = oldstr.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' ');
after first .replace()
of leading , trailing whitespace removed, leaving internal spaces. replace runs of 1 or more space/tab/newline single space.
one other way go reduce runs of whitespace single space, trim 1 remaining leading , trailing space:
var oldstr = "\n\t\t\t \n\n\t \n\t \t\tfood , 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 es5.1 (ecma-262) polyfill .replace(/^\s+|\s+$/g, '')
(with couple of other characters added) anyway.
Comments
Post a Comment