Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In input i write any sentence with multiple spaces,after clicking on Space Remover button,i need to replace that multiple spaces with single and show it in h1 tag.

What I have tried:

I have tried like this, but it's not working.

<input id="bar" type="text" placeholder="Type a sentence...">
		<button onclick="spaceremover()">Space Remover</button>
		<h1 id="result1"></h1>


function spaceremover(){
	var a = document.getElementById("bar").value;
	for(var i = 0; i < a.length;i++){
	a.replace(/\s/g, ' ');	
	}
	document.getElementById("result1").innerHTML = a;
}
Posted
Updated 16-Jul-18 23:12pm
v2

Your regex replaces only single white space characters (\s) with a single space. To match sequences of multiple spaces, you have to specify that by appending a + (match one or more occurences) or {2,} (match two or more occurences).

There is also no need to use a loop when using the regex global option.

Finally, the String.prototype.replace() - JavaScript | MDN[^] function returns a new string where the replacement has been performed but does not alter the original string

So use (untested):
JavaScript
function spaceremover(){
    var a = document.getElementById("bar").value;
    document.getElementById("result1").innerHTML = a.replace(/\s{2,}/g, ' ');
}
 
Share this answer
 
Comments
Suren97 16-Jul-18 6:29am    
Thank you very much :)
Jochen Arndt 16-Jul-18 6:43am    
You are welcome.
Suren97 16-Jul-18 6:51am    
I have one problem too, can you help me please?
https://www.codeproject.com/Questions/1252529/Javascript-how-to-replace-word-in-textarea
Jochen Arndt 16-Jul-18 7:15am    
Done.
Not much different to this question besides using a search pattern known only at runtime.
you can use
.replace(/\d+/, '') 

or
.split('/\d+/').join(' ')


.split('  ').join(' ')

or
str.replace( /\s\s+/g, ' ' )

or

var str = "       Hello World!       ";
   alert(str.trim());

and this one most used in this case
myStr.replace(/  +/g, ' ')


it would be worthful.
 
Share this answer
 
v2
Comments
Suren97 16-Jul-18 6:27am    
It doesn't work. I think the problem is in loop or another.
var myStr = 'The     quick   brown  fox';
    alert(myStr);  // Output 'The     quick   brown  fox'
    
    var newStr = myStr.replace(/  +/g, ' ');
    alert(newStr);  // Output 'The quick brown fox'

document.getElementById("result1").innerHTML = newStr;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900