0 day streak
javascript / beginner
Snippet

Removing Whitespace with String.trim()

The trim() method removes whitespace from both the beginning and the end of a string. This is a best practice in forms to ensure that leading or trailing spaces entered by users don't break search queries or database lookups.

snippet.js
javascript
1
2
3
4
5
6
7
function SearchInput() {
function validate(input) {
const clean = input.trim();
console.log('Searching for: ' + clean);
}
return <input onBlur={function(e) { validate(e.target.value); }} />;
}
nextjs
Breakdown
1
input.trim()
Creates a new string with all invisible spaces at the start and end removed.