Test:
var string = ' fsajdf asdfjosa fjoiawejf oawjfoei jaosdjfsdjfo sfjos 2324234 sdf safjao j o sdlfks dflks l '
string.replace(/^\s+|\s+$|\s+(?=\s)/g, '')
string.trim()
Results:
Function | Result |
---|---|
regex | regex x 1,458,388 ops/sec ±2.11% (62 runs sampled) |
trim | trim x 7,530,342 ops/sec ±1.22% (62 runs sampled) |
Conclusion:
trim
is faster
Source:
https://www.measurethat.net/Benchmarks/Show/4767/0/regex-removing-whitespace-vs-trim
solved Which is more faster? trim() or RegEx?