Trim a String in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to trim a string in JavaScript. Trim a string means to remove white spaces from both ends of a string. In JavaScript, we can trim a string using in-built trim() method or using regex.

Example 1: Trim a String using trim() method

const string = "  Hello   ";
const result = string.trim();
console.log(string.trim());

Output

Hello

Example 2: Trim a String using Regex

const string = "  Hello   ";
let result = string.replace(/^\s+|\s+$/gm,'');
console.log(result);

Output

Hello