We can use trimEnd() in situations where we want to remove whitespace from the end of a string, but not from the beginning or middle. For example, if we are working with user input and want to remove any trailing whitespace before processing the input, we can use trimEnd() to ensure that the input is clean and consistent
To show how that can work, let us create a simple webpage with an input textbox where a user can type a string and lets place a button which upon clicking will invoke the trimEnd() method and display the trimmed string. To make sure it really trimmed it, we will append a dollar character at the end of the string (so it makes it clear there are no whitespace characters on the page). Here is some code to do precisely this:
In the above code, we create an HTML page with a label, an input textbox, a button, and a paragraph element. We also include a script that defines a function called trimInput(). When the button is clicked, the trimInput() function is called. The function gets the value of the input textbox, trims the whitespace from the end of the string using trimEnd(), adds the dollar character, and sets the text content of the paragraph element to the trimmed string.
Below is an example of how this works (we typed Kodeclik followed by some space characters in the textbox):
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.