Skip to content

Instantly share code, notes, and snippets.

@manstie
Created January 6, 2022 07:20
Show Gist options
  • Save manstie/f1c2637b001bbd7fa3aa137713a26138 to your computer and use it in GitHub Desktop.
Save manstie/f1c2637b001bbd7fa3aa137713a26138 to your computer and use it in GitHub Desktop.
Trim all whitespace
/**
* Trims https://invisible-characters.com/ with unicode regex, falls back to trim if unicode regex not supported.
*/
function trimAllWhitespace(str) {
const whitespace = '\\s\u00AD\u034F\u061C\u115F\u1160\u17B4\u17B5\u180E\u2000-\u200F\u202F\u205F-\u2064\u206A-\u206F\u3000\u2800\u3164\uFEFF\uFFA0\u{1D159}\u{1D173}-\u{1D17A}';
try {
const re = new RegExp(`^[${whitespace}]+|[${whitespace}]+$`, 'gu');
return str.replace(re, '');
} catch(e) {
return str.trim();
}
}
trimAllWhitespace('abc ­͏؜ᅟᅠᅠ឴឵᠎            ​‌‍‎‏  ⁡⁢⁣⁤ ⠀⠀ㅤᅠ𝅙𝅳𝅴𝅵𝅶𝅷𝅸𝅹𝅺');
/**
* Trims https://invisible-characters.com/
*/
function trimAllWhitespace(string $str): string
{
return trim($str, " \t\n\r\0\v\u{00AD}\u{034F}\u{061C}\u{115F}\u{1160}\u{17B4}\u{17B5}\u{180E}\u{2000}..\u{200F}\u{202F}\u{205F}..\u{2064}\u{206A}..\u{206F}\u{3000}\u{2800}\u{3164}\u{FEFF}\u{FFA0}\u{1D159}\u{1D173}..\u{1D17A}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment