Explain String.trimStart() & String.trimEnd() methods in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

The String.trimStart() method is used to remove whitespace from the string beginning while the String.trimEnd() method removes whitespace from the end of the string.

Following is the code for the String.trimStart() and String.trimEnd() methods −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
<h1>String.trimStart() and String.trimEnd() methods</h1>
<div&g;<pre class="sample"></pre></div>
<div style="color: green;"><pre class="result"></pre></div>
<button class="Btn">CLICK HERE</button>
Click on the above button to trim the above string from start and end
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let str = " HELLO WORLD ";
   sampleEle.innerHTML = str;
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = "trimStart() :" + str.trimStart() + "|<br>";
      resEle.innerHTML += "trimEnd() :" + str.trimEnd() + "|";


The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on 16-Jul-2020 08:38:55