How can i match a series of expressions with OR’s? This is for scrubbing plain text data which may contain imbedded spaces or tabs at the front of each row. This is in preparation for a .split at newlines.
const oldStr = `abc
abc
abc`;
I want to replace:
newline + 0 or more spaces OR tabs
with
newline
This achieves what i want
newStr = oldStr.replaceAll(/\n */g, "\n"); // newline + spaces
newStr = newStr.replaceAll(/\n\t*/g, "\n"); // newline + tabs
How to do that in a single statement? The following fail:
Attempt, with pipe:
newStr = oldStr.replaceAll(/\n *|\t*/g, "\n");
Attempt, with parens around the OR:
newStr = oldStr.replaceAll(/\n( *|\t*)/g, "\n");
Attempt, with slashes around the OR:
newStr = oldStr.replaceAll(/\n/ *|\t*/g, "\n");
Attempt, with square brackets instead of pipe:
newStr = oldStr.replaceAll(/\n[ *\t*]/g, "\n");
Attempt, with quotes and pipe:
newStr = oldStr.replaceAll("\n *\t|*/g", "\n");
Attempt, with quotes and pipe and parens:
newStr = oldStr.replaceAll("\n( *|\t*)/g, "\n");
Attempt, with quotes and square brackets:
newStr = oldStr.replaceAll("\n[ *\t*]/g", "\n");
Feel free to offer a solution which combines the cleaning with a .split statement, or a non-regex solution.
>Solution :
You don’t need to "prepare" for splitting, just split by \n, optionally surrounded by spaces:
text = ` How razorback-jumping
frogs
can
\t level six \t
\t piqued gymnasts!`
console.log(text.trim().split(/[ \t]*\n[ \t]*/g))