OneBite.Dev - Coding blog in a bite size

trim a string in Javascript

Code snippet on how to trim a string in Javascript

  let str = '   The quick brown fox jumps over the lazy dog   ';
  let trimmedStr = str.trim();
  
  console.log(trimmedStr);  

This code is written in Javascript. Here, we are trimming a provided string of “The quick brown fox jumps over the lazy dog”. The first line creates a string variable called str, which contains the sentence, along with some whitespace characters at the beginning and end. The second line uses the trim function to create a new string variable, trimmedStr, which has the same contents, but with the whitespaces removed. The third line logs the trimmedStr variable to the console. In other words, all the whitespace at the beginning and end of the string will be removed, leaving the sentence intact.

javascript