How to Trim a String in JavaScript? (3 Programs)
Trimming a string means removing extra spaces or specific unwanted characters from the beginning and end of a string. It is often used to clean up user input, format data to meet specific requirements, or ensure consistent outputs in applications. This is especially important in scenarios like validating form entries, processing strings in databases, or standardizing input for further processing.
In this guide, you will learn how to trim a string in JavaScript using various approaches, including built-in methods like trim() and custom solutions for trimming specific characters.
Trim a String in JavaScript Using trim() Method
The simplest way to trim a string in JavaScript is by using the built-in trim() method.
Code
function trimString(str) {
return str.trim();
}
// Test the function
const input = " Hello, JavaScript! ";
console.log(`Original: '${input}'`);
console.log(`Trimmed: '${trimString(input)}'`);
Output
Original: ' Hello, JavaScript! '
Trimmed: 'Hello, JavaScript!'
Explanation
The trim() method removes whitespace from both the beginning and end of the string.
Trimming Start and End Separately in JavaScrpt
You can use the trimStart() and trimEnd() methods to remove whitespace from either the beginning or the end of the string.
Code
function trimStartAndEnd(str) {
const trimmedStart = str.trimStart();
const trimmedEnd = str.trimEnd();
return { trimmedStart, trimmedEnd };
}
// Test the function
const input = " Hello, World! ";
const result = trimStartAndEnd(input);
console.log(`Trimmed Start: '${result.trimmedStart}'`);
console.log(`Trimmed End: '${result.trimmedEnd}'`);
Output
Trimmed Start: 'Hello, World! '
Trimmed End: ' Hello, World!'
Explanation
-
trimStart() removes whitespace only from the start of the string.
-
trimEnd() removes whitespace only from the end of the string.
Trim a String in JavaScript Using Regular Expressions
You can use regular expressions to remove whitespace or specific characters from the start and end of a string.
Code
function trimUsingRegex(str) {
return str.replace(/^\s+|\s+$/g, '');
}
// Test the function
const input = " Learn JavaScript ";
console.log(`Trimmed with Regex: '${trimUsingRegex(input)}'`);
Output
Trimmed with Regex: 'Learn JavaScript'
Explanation
-
^\s+ matches whitespace at the beginning of the string.
-
\s+$ matches whitespace at the end of the string.
-
g ensures global replacement.
Trimming in JavaScript Using Custom Characters
You can extend the functionality to trim specific characters from the start and end of a string.
Code
function trimCustomCharacters(str, chars) {
const regex = new RegExp(`^[${chars}]+|[${chars}]+$`, 'g');
return str.replace(regex, '');
}
// Test the function
const input = "---JavaScript---";
console.log(`Custom Trim: '${trimCustomCharacters(input, '-')}'`);
Output
Custom Trim: 'JavaScript'
Explanation
-
The custom character set is used in the regular expression to match and remove specific characters.
Concepts Used in Above Programs
String Methods
-
trim(), trimStart(), and trimEnd() simplify the process of removing whitespace.
Regular Expressions
-
Regular expressions provide a flexible way to handle trimming for both whitespace and custom characters.
Customization
-
Using dynamic character sets allows trimming of specific unwanted characters.