To trim a string in JavaScript, you can use the trim()
method of the String class.
In this example,
str1
with a value of " Hello World "
.trim()
method on str1
to remove leading and trailing whitespace characters.let str1 = " Hello World ";
let trimmedStr1 = str1.trim();
console.log(`Trimmed string is: '${trimmedStr1}'`);
Trimmed string is: 'Hello World'
In this example,
str2
with a value of " apple"
.replace()
method with a regular expression to remove leading whitespace characters.let str2 = " apple";
let trimmedStr2 = str2.replace(/^\s+/, '');
console.log(`Trimmed string is: '${trimmedStr2}'`);
Trimmed string is: 'apple'
In this example,
str3
with a value of "banana "
.replace()
method with a regular expression to remove trailing whitespace characters.let str3 = "banana ";
let trimmedStr3 = str3.replace(/\s+$/, '');
console.log(`Trimmed string is: '${trimmedStr3}'`);
Trimmed string is: 'banana'
In this tutorial, we learned How to Trim a String in JavaScript language with well detailed examples.