squish function
Trims a text and collapses every run of whitespace, line breaks included, into a single space.
ts
import { squish } from 'utils';Signature
ts
export function squish(input: string): stringParameters
| Name | Description |
|---|---|
input | The text. |
Returns
The text on one line, without leading, trailing or repeated whitespace.
Example
ts
squish(' Engine\n room temperature \t'); // 'Engine room temperature'Tests
Line coverage: 100 %.
- ✅ squishes " Engine\n room temperature \t"
- ✅ squishes "already clean"
- ✅ squishes " "
Source
src/string/squish.ts (on GitHub)
Source code
ts
const WHITESPACE_RUN_PATTERN = /\s+/gv;
/**
* Trims a text and collapses every run of whitespace, line breaks included, into a single space.
*
* @param input - The text.
* @returns The text on one line, without leading, trailing or repeated whitespace.
* @example
* squish(' Engine\n room temperature \t'); // 'Engine room temperature'
*/
export function squish(input: string): string {
return input.trim().replaceAll(WHITESPACE_RUN_PATTERN, ' ');
}Test file
ts
import { squish } from './squish';
describe(squish, () => {
it.for([
[' Engine\n room temperature \t', 'Engine room temperature'],
['already clean', 'already clean'],
[' '.repeat(3), ''],
] as const)('squishes %j', ([input, expected]) => {
expect(squish(input)).toBe(expected);
});
});Keywords: squish, strings, function