How do you trim a character in javascript?
Update: Was curious around the performance of different solutions and so I've updated a basic benchmark here: https://www.measurethat.net/Benchmarks/Show/12738/0/trimming-leadingtrailing-characters Show Some interesting and unexpected results running under Chrome. https://www.measurethat.net/Benchmarks/ShowResult/182877
Please note; tests were carried out on only a single test string (with both leading and trailing characters that needed trimming). In addition, this benchmark only gives an indication of raw speed; other factors like memory usage are also important to consider. If you're dealing with longer strings I believe this should outperform most of the other options by reducing the number of allocated strings to either zero or one:
Or if you want to trim from a set of multiple characters:
EDIT: For fun, trim words (rather than individual characters) Example 1Remove spaces with trim(): let text = " Hello World! "; Try it Yourself » Remove spaces with replace() using a regular expression: let text = " Hello World!
"; Try it Yourself » Definition and UsageThe The SyntaxParametersReturn Value
Browser Support
ES5 (JavaScript 2009) fully supported in all browsers:
String trimming is one of the most common tasks that programmers deal with. Trimming functions remove whitespace from the beginning and/or end of a string. Native support for trimming was introduced in JavaScript 1.8.1, meaning that they were not part of Internet Explorer prior to IE9. This article will show you how to trim, and how you can build more flexible and powerful trimming functions. JavaScript provides three functions for performing various types of string trimming.
The first,
|