If you want to check if string contains only spaces in JavaScript, I will share two methods to do this: trim()
and replace()
methods. Let’s go into detail about each solution below.
Check if string contains only spaces in Javascript
Using the trim() method
We can access the length property of the string and compare this value with 0
to check if the string contains only the whitespace.
To check if strings contain only spaces, we can trim all the spaces in the string and use the trim() method in Javascript before comparing the length of the trimmed string with 0
. If the string after trimming whitespace is equal to 0
, then the string contains only spaces.
Code sample:
function checkSpaces(str){
// Check the length of the string after trimming all the spaces
if(str.trim().length == 0){
console.log("String contains only spaces");
}
else console.log("String does not contain only spaces");
}
let str1= 'Learn';
let str2= ' ';
let str3= ' Share';
let str4= ' IT ';
checkSpaces(str1);
checkSpaces(str2);
checkSpaces(str3);
checkSpaces(str4);
Output
String does not contain only spaces
String contains only spaces
String does not contain only spaces
String does not contain only spaces
Using the replace() method
Also, to remove all the whitespace in the string and check if the string contains only spaces, we can use the replace() method in Javascript to replace all the spaces in the string with an expression regular /\s/g. Check the length of a string after removing all spaces with an if-else conditional.
Code sample:
function checkSpaces(myStr){
// Check the length of the string after removing all the whitespaces
if(!myStr.replace(/\s/g, '').length){
console.log("String contains only spaces");
}
else console.log("String does not contain only spaces");
}
let str1= 'Le arn ';
let str2= ' ';
let str3= ' I T ';
checkSpaces(str1);
checkSpaces(str2);
checkSpaces(str3);
Output
String does not contain only spaces
String contains only spaces
String does not contain only spaces
Summary
Above, I showed you how to check if String contains only spaces in JavaScript with the trim()
and replace()
methods. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!
Maybe you are interested:
- Remove all Numbers from a String in JavaScript
- Convert Integer to its Character Equivalent in JavaScript
- Remove Substring From String in JavaScript

Hi, my name is Joni Smith. My job is a programmer. I love learning programming languages, especially C++, C#, php, javascript, html, css. I want to share them with you. I hope my articles will bring a lot of useful knowledge to you.
Name of the university: HVNH BA
Major: htttql MIS
Programming Languages: C++, C#, php, javascript, html, css