Explain Codes LogoExplain Codes Logo

Trim string in JavaScript

javascript
trim
polyfill
regex
Nikita BarsukovbyNikita Barsukov·Aug 18, 2024
TLDR

Breeze through string trimming with JavaScript using the .trim() method to wipe out whitespaces on both sides:

let str = " Spaces, the final frontier "; console.log(str.trim()); // "Spaces, the final frontier"

Fallback to a polyfill or a regular expression, for the times when .trim() hasn't made its grand entry:

if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); // Cue Space Oddity by Bowie }; }

Polyfill playground

Building a polyfill for trim

Older browsers that don't support .trim(), a polyfill is your savior. It sweeps in and adds the functionality if it doesn't exist.

if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); // Nostalgic feel of a vinyl, isn't it? }; }

While this code makes .trim() rock in older browsers, also makes you feel like you own a time machine.

The jQuery junction

Deploying $.trim()

Working in a jQuery environment, or dealing with phantom values like undefined or null, the $.trim() function is your secret weapon:

let result = $.trim(undefinedVariable); // result is an empty string, like my coffee cup at 5pm

This ninja jQuery method turns undefined and null into an empty string, making it a trusted ally for adventurous coders.

Custom trim toolkit

Crafting custom trim functions

For those special occasions when you need to trim characters other than whitespace, a handmade trim function becomes an invaluable asset:

function trimChar(string, charToRemove) { while(string.charAt(0) == charToRemove) { string = string.substring(1); } while(string.charAt(string.length - 1) == charToRemove) { string = string.substring(0, string.length - 1); } return string; } console.log(trimChar("--Not all heroes wear capes--", "-")); // "Not all heroes wear capes"

Regex ring

trim methods: a performance showdown

When it comes to speed, built-in methods like .trim() usually skim past regular expressions. However, for those rebellious days when .trim() is not around, regular expressions are your comrades:

let trimmed = " Fast and Furious ".replace(/^\s+|\s+$/g, ''); console.log(trimmed); // "Fast and Furious"

Don't forget that while regular expressions can make magic happen, they could also turn your code into a slug fest if overused.

Beyond regular whitespaces

Spaces: the BOM and NBSP saga

When you run into Byte Order Marks (BOM) or Non-Breaking Spaces (NBSP), your regular trim tools might need an upgrade. Not all whitespaces wear the same cloak:

let stringWithNBSP = "Hello,\u00A0World!"; console.log(stringWithNBSP.trim()); // "Hello, World!"

In cases like this, .trim() doesn't sweep away the NBSP, and you need a beefed-up regex as your cleanup crew:

let stringWithNBSP = "Hello,\u00A0World!"; console.log(stringWithNBSP.replace(/\u00A0/g, '')); // "Hello,World!"

Deep dive into trimming

Advanced trim tactics

Eager for advanced trimming methods and tips on performance? Steven Levithan's blog post in the references might just satiate your curiosity. Be ready for some deep trim() diving!

Compatibility Chronicles

The Chronicles of trim() and ECMAScript 5

Using .trim(), it's a good habit to check compatibility with ECMAScript 5. It's like double-checking your parachute before a dive:

- `.trim()` is part of the ECMAScript 5 standard. - Fully supported in all modern browsers. - Cross-check compatibility if stepping into older environments.