Remove whitespace from the end of a string using JavaScript : trimEnd() , trimRight()

Java Script @ Freshers.in

JavaScript’s trimEnd() method, alternatively known as trimRight(), is utilized to remove whitespace from the end of a string. This includes all sorts of whitespace characters (like spaces, tabs, and line breaks) found at the string’s end. It’s important to note that trimEnd() doesn’t alter the original string; instead, it returns a new string with the whitespace at the end removed. The trimEnd() method in JavaScript is a specialized tool tailored for scenarios necessitating the removal of unwanted whitespace at the conclusion of strings.

Syntax:

The syntax of the trimEnd() method is quite straightforward:

string.trimEnd()

This method doesn’t require any parameters and it returns a new string with the trailing whitespace eliminated.

Examples and execution:

The examples provided can be executed in any standard JavaScript environment, including browser consoles, online code playgrounds, or a local Node.js setup.

Basic usage:

let farewell = "Goodbye, World!   ";
let trimmedFarewell = farewell.trimEnd();
console.log(trimmedFarewell); // Outputs: "Goodbye, World!"
Cleaning user input:
function cleanInput(input) {
    let cleanedInput = input.trimEnd();
    console.log("Cleaned input:", cleanedInput);
}

let userInput = "Learning JavaScript is fun!   ";
cleanInput(userInput); // Outputs: "Cleaned input: Learning JavaScript is fun!"
Using alongside other string methods:
let string = "   JavaScript is ubiquitous!   ";
let processedString = string.trimEnd().toLowerCase();
console.log(processedString); // Outputs: "   javascript is ubiquitous!"
Example – Preparing user comments
function prepareComment(comment) {
    let preparedComment = comment.trimEnd();
    // Further comment processing
    console.log("Prepared comment:", preparedComment);
}
let userComment = "Can't wait for the next JavaScript update!      ";
prepareComment(userComment); // Outputs: "Prepared comment: Can't wait for the next JavaScript update!"

Get more articles on Java Script

Read more on Shell and Linux related articles

Refer more on python here :

Author: user