Skip to content

13. Trim (pT.js) *The Best Trim I Have Found*

Pimp Trizkit edited this page Mar 24, 2018 · 5 revisions
<< Previous        Back to Table of Contents        Next >>

    "Now thats some good trim." - PT

This will trim that white space right-out from around that big string of yours, faster than you can say "unzip". It can get white space that you didn't even know about and it's the fastest version I've ever tested (...that also gets most of the odd-ball space white). Sure, there are faster but less accurate ways to do it. This method actually combines some of those into one for increased accuracy with great speed. Or there are other ways that cover that last 1% of accuracy, but for the cost of a lot slower.

Anyhow... Credit to someone, somewhere, I didn't write it originally. And I can't find who did, kudos to you, John Doe. I just rewrote/update/refactored it. Just try to beat it's speed on a variety of string sizes, and amounts/types of white space. And I will replace this method if you succeed and give you all the credit.

Code:

const pT=(s)=>{if(!s||typeof(s)!="string")return "";var s=s.replace(/^\s\s*/,''),w=/\s/,i=s.length;while(w.test(s.charAt(--i)));return s.slice(0,i+1);}

Usage:

let s = pT("   Where does White Space *actually* come from? And then that begs a question, do we use Black Space to remove it? Can space be Purple or Plaid? And whatever happened to My Space?     ");

Return:

A copy of the specified string but with white space removed from the beginning and end. Or "" if a non-string was passed in for s.

Params:

pT(s)

s = < Trim String > * REQUIRED

  • The string from which a copy is made and white space is removed from the front and back, and then the modified copy is returned.