How to Remove Spaces from String in JavaScript
Abstract: assign a string with spaces to a variable. Then use JavaScript trim() function to remove leading and trailing spaces from the string. str=" W
Question – How to remove extra spaces from a string using JavaScript?
A space (」 「) character is used to separate two words. Some times we get the extra spaces in a string, which may case issues with your application.
JavaScript trim()
function is used for removing leading (before) and trailing (after) spaces from a string. This tutorial will help you to remove extra spaces from a string using JavaScript function.
For the example, assign a string with spaces to a variable. Then use JavaScript trim()
function to remove leading and trailing spaces from the string.
Output:
Welcome to TecAdmin.net!JavaScript Remove Spaces Anywhere in String
You can remove all spaces from a string with combination of JavaScript split()
and join()
functions. Here we will split the string with space characters as delimiter. The again join the all parts of string without any space.
You can also run both functions in single line.
<script> str="Welcome to TecAdmin.net "; newStr = str.split(" ").join(""); console.log(newStr); </script>12345<script> str="Welcome to TecAdmin.net "; newStr = str.split(" ").join(""); console.log(newStr);</script>Output:
WelcometoTecAdmin.netUsing Left or Right Trim in JavaScript
Some of the older browsers may not support JavaScript trim() function. In that case, we can use the replace() method to remove trailing and preceding white spaces from any string.
- Trim Space Both Side:
alltrimStr = str.replace(/^s+|s+$/gm,'');1alltrimStr = str.replace(/^s+|s+$/gm,''); - Trim Spaces Left Side:
ltrimStr = str.replace(/^s+/,'');1ltrimStr = str.replace(/^s+/,''); - Trim Spaces Right Side:
rtrimStr = str.replace(/s+$/,'');1rtrimStr = str.replace(/s+$/,'');
This tutorial described you to remove extra spaces from a string using JavaScript. Additionally, provides you instructions to remove all spaces from a string.