How to trim a JS string?
The best way to trim a string in JavaScript is to use the trim() method:
const myString = ' string to trim ';
// Should display: "string to trim"
console.log (myString.trim());
For browsers who do not support the trim() method, running the following code before any other code will create a polyfill trim() method (from MDN):
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
The best way to trim a string in JavaScript is to use the trim() method:
const myString = ' string to trim ';
// Should display: "string to trim"
console.log (myString.trim());
For browsers who do not support the trim() method, running the following code before any other code will create a polyfill trim() method (from MDN):
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
| # | ID | Query | URL | Count |
|---|---|---|---|---|
| 0 | 13332 | alphons | https://en.ans.wiki/50/how-to-trim-a-js-string | 1 |
| 1 | 13222 | en | https://en.ans.wiki/50/how-to-trim-a-js-string | 3 |