This method doesn’t modify the original string. It removes whitespace from both ends of the string and returns this new string.
An example of str.trim() method :
var str1 = " Hello World "; var str2 = ` Hello World `; console.log(str1); console.log(str2); console.log("Trim :") console.log(str1.trim()); console.log(str2.trim());
It will print the below output :
Hello World Hello World Trim : Hello World Hello World
As you can see here, trim() removed the whitespace characters from both end for both str1 and str2.
Similar to trim(), we have two more methods called trimStart and trimEnd to remove whitespace characters from the start and end of a string. Let’s try this method with the same example we have seen above :
var str1 = " Hello World "; var str2 = ` Hello World `; console.log(str1); console.log(str2); console.log("Trim :") console.log(str1.trimStart()); console.log(str2.trimStart());
Here, only the starting whitespace characters are removed. Similarly, if we use trimEnd(), it will produce one output like below :