Problems › JavaScript › text
Tidy up pasted text
Text pasted from a spreadsheet arrives with tabs, newlines and runs of spaces in it. The search box wants one clean line.
- Every run of whitespace becomes a single space.
- No leading or trailing space is left.
- Text that is nothing but whitespace comes back empty.
normaliseSpace(text: string) → string
Where you start
function normaliseSpace(text) {
}
Worked examples
| Call | Result |
|---|---|
normaliseSpace(" hello world ") | "hello world" |
normaliseSpace("a\tb\nc") | "a b c" |
normaliseSpace("already clean") | "already clean" |
normaliseSpace(" ") | "" |
Hint
Splitting on whitespace and joining with a single space does both jobs at once.
Reference solution in JavaScript
function normaliseSpace(text) {
return text.split(/\s+/).filter((w) => w.length > 0).join(' ');
}