Removing whitespace from both ends of a string using JavaScript : trim()

Java Script @ Freshers.in

JavaScript’s trim() method is used to remove whitespace from both ends of a string. Whitespace in this context includes all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). This method does not affect the value of the string itself but instead returns a new string with the whitespace trimmed off.

Syntax:

The trim() method is straightforward and easy to use:

string.trim()

This method does not take any parameters, and it returns a new string with whitespace removed from both sides of the original string.

Examples and Execution:

The examples below can be run in any standard JavaScript environment — this includes your browser’s developer console, any online code playground, or a local Node.js environment.

Basic usage
let originalString = "   Hello, World!   ";
let trimmedString = originalString.trim();
console.log(trimmedString); // Outputs: "Hello, World!"
Login form validation:
function validateUsername(username) {
    let trimmedUsername = username.trim();
    if(trimmedUsername.length === 0) {
        console.log("Username cannot be empty!");
    } else {
        console.log("Username is valid!");
    }
}
// Simulating user input
let userInput = "    ";
validateUsername(userInput); // Outputs: "Username cannot be empty!"

Removing new lines:

let stringWithNewLines = "\n\nHello, World!\n\n";
let trimmedString = stringWithNewLines.trim();
console.log(trimmedString); // Outputs: "Hello, World!"
Practical use case – Processing user input:
function processInput(input) {
    let trimmedInput = input.trim();
    // Proceed with further processing
    console.log("Processed input:", trimmedInput);
}

let userEnteredData = "   John Doe   ";
processInput(userEnteredData); // Outputs: "Processed input: John Doe"
Author: user