Question #50   Submitted by Answiki on 06/06/2020 at 03:26:44 PM UTC

How to trim a JS string?

Answer   Submitted by Answiki on 06/06/2020 at 03:23:57 PM UTC

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

6 events in history
Question by Answiki 06/06/2020 at 03:26:44 PM
How to trim a JS string?
Question by Answiki 06/06/2020 at 03:26:32 PM
How to trim a JavaScript string?
Question by Answiki 06/06/2020 at 03:25:05 PM
How to trim a string in JS?
Question by Answiki 06/06/2020 at 03:24:57 PM
How to trim a string in JavaScript?
Question by Answiki 06/06/2020 at 03:24:45 PM
Trim a string in JS?
Answer by Answiki on 06/06/2020 at 03:23:57 PM

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

Icons proudly provided by Friconix.