Skip to main content

Overview


.trim() method


Removes leading and trailing spaces from the string body.

let email = "  alex@gmail.com  "
email.trim() // "alex@gmail.com"

You need to assign the value to the original binding. Also, don't forget to return at the end. This is incorrect:

function getEmail(email) {
let cleaned = email
cleaned.toLowerCase()
cleaned.trim()
return cleaned
}

Quick Recap


  • The .trim() method allows us to make a new copy of the string while removing leading and trailing spaces from the original string.
  • The .trim(), .toLowerCase(), and .toUpperCase() methods create new copies of the variable and do not change the original variable.
  • To change the variable, you have to re-assign it to itself with the function call. For example: cleaned = cleaned.trim() will change the value of cleaned and make it trimmed.