To remove whitespaces from both ends of a string, you must use the String.prototype.trim()
method.
It is important to note that in JavaScript following characters are considered whitespaces:
The syntax for the trim() method is
let trimmedString = originalString.trim();
Note: The trim()
method does not modify the original string and returns a new string with whitespaces removed from both ends.
The following example removes whitespaces from a string.
let str = " JavaScript String "; let trimmedString = str.trim(); console.log(trimmedString); console.log(str);
Output
"JavaScript String" " JavaScript String "