How to trim a string in JavaScript?
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 |
---|