JavaScript String trim() Method
The JavaScript String trim() method removes white spaces from both sides of a string and returns a new string. If the original string has no white spaces at the beginning or end, it returns the same string.
To remove whitespace characters from only one end of a string, you can use the trimStart() or trimEnd() methods, depending on which end you want to trim.
Syntax
Following is the syntax of JavaScript String trim() method −
trim()
Parameters
- It does not accept any parameters.
Return value
This method returns a new string after removing white-spaces from both its beginning and end.
Example 1
If the original string has no white spaces at both the ends, it returns the same string.
<html>
<head>
<title>JavaScript String trim() Method</title>
</head>
<body>
<script>
const str = "Tutorials Point";
document.write("Original string: ", str);
document.write("<br>New string: ", str.trim());
</script>
</body>
</html>
Output
The above program returns "Tutorials Point".
Original string: Tutorials Point New string: Tutorials Point
Example 2
In this example, we use the JavaScript String trim() method to remove the whitespace from both ends of the string " Hello World! ".
<html>
<head>
<title>JavaScript String trim() Method</title>
</head>
<body>
<script>
const str = " Hello World! ";
document.write("Original string: ", str);
document.write("<br>Length of original string: ", str.length);
document.write("<br>New string: ", str.trim());
document.write("<br>Length of new string: ", str.trim().length);
</script>
</body>
</html>
Output
After executing the above program, it trimmed the white spaces from both ends and returned a new string "Hello World!".
Original string: Hello World! Length of original string: 14 New string: Hello World! Length of new string: 12
Example 3
Let's see the real-time usage of the JavaScript String trim() method. This method can be used to prevent users from logging in with an empty username and password in the input field.
<html>
<head>
<title>JavaScript String trim() Method</title>
</head>
<body>
<input type="text" placeholder="Username" id = 'uname'>
<br><br>
<input type="password" placeholder="Password" id = 'psw'>
<br><br>
<button onclick="Login()">Submit</button>
<span id = 'msg'></span>
<script>
function Login(){
let uname = document.getElementById("uname").value;
let psw = document.getElementById("psw").value;
let msg = document.getElementById("msg");
if(uname.trim().length == 0){
msg.innerHTML = "Username can't be empty...!";
}
else if(psw.trim().length == 0){
msg.innerHTML = "Password can't be empty...!";
}
else{
msg.innerHTML = "Submitted successfully...!";
}
}
</script>
</body>
</html>
Output
The program displays a UI in the top left corner of the screen. It has two input fields for username and password, and a button. If the fields are blank and the button is clicked, some error messages appear near the button.