👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.
Trim a string in JS?

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, '');