JavaScript trim() Method
JavaScript trim() method is used to remove either white spaces from the given string. This method returns a new string with removed white spaces. This method is called on a String object. This method doesn’t accept any parameter.
Example: This example describes the JavaScript String trim() method.
let gfg = 'GFG ';
let geeks = 'stands-for-w3wiki';
// Storing new object of string
// with removed white spaces
let newGfg = gfg.trim();
// Old length
console.log(gfg.length);
// New length
console.log(newGfg.length)
Output
7 3
Explanation:
The code initializes two strings, gfg and geeks. It then uses the trim() method to remove leading and trailing whitespace from the string gfg, storing the result in newGfg. The code prints the lengths of the original string gfg (including whitespace) and the trimmed string newGfg (excluding whitespace) to the console.
JavaScript String Methods
JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing.
JavaScript provides a bunch of string methods for representing and manipulating strings. From retrieving specific characters with charAt(), converting strings to uppercase with toUpperCase(), to combining strings with concat(), these methods simplify a wide range of tasks for developers. In this article, we will explore some essential JavaScript string methods that every developer should be familiar with.