Inside this article we will see the concept i.e Javascript how to remove extra spaces from string. In a string, spaces in terms of either normal spaces between words, tabs space in a string, new lines, etc.
All these tabs spaces, new lines, etc will be removed once we implement this concept. If you are wondering to find a solution for removal of extra spaces from string including new lines then this article will help you a lot.
Extra spaces means –
, tabs, \n new lines
Learn More –
- HTML5 Video Slider Using Owl Carousel jQuery Plugin
- Javascript Auto Logout in CodeIgniter 4 Tutorial
- JavaScript Convert Hexadecimal Color Code into RGB Format
- Javascript How To Remove Extra Spaces From String
Let’s get started.
Create Simple Application
Here, we will create an application in HTML and using javascript which removes extra spaces from a string value.
Create a file remove-space.html in your localhost directory.
Open file and write this following code into it.
<script> var stringWithLineBreaks = ` Online Web Tutor project I've got Breaks `; console.log(removeNewlines(stringWithLineBreaks)); function removeNewlines(str) { //remove line breaks from str str = str.replace(/\s{2,}/g, ' '); str = str.replace(/\t/g, ' '); str = str.toString().trim().replace(/(\r\n|\n|\r)/g,""); console.log(str); } </script>
Concept
Here, is the code to remove all spaces from string.
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
Application Testing
Open project into browser.
URL: http://127.0.0.1/js/remove-space.html
Output
Online Web Tutor project I've got Breaks
We hope this article helped you to learn Javascript How To Remove Extra Spaces From String in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.