0

look at the following question:

Remove whitespaces inside a string in javascript [closed]

according to the accepted answer string.replace(" ","") will remove all the white space

but in my case i have the following string:

var ctr = " #d1 { width: 100px ; height: 100px ; background-color: #000 ; opacity: 1 ; margin-left : 0px ; } "

now i tried to replace all the extra white spaces:

 var ctrWithNoWhiteSpaces = ctr.replace(" ", ""); //returns spaces full string 

function s(){


var ctr = " #d1 {       width: 100px ; height: 100px ; background-color: #000 ; opacity: 1 ; margin-left : 0px ; } ";
  
  alert(ctr);
  
  ctr = ctr.replace(" ", "");
  
  alert(ctr);


}
<button onclick="s()">click</button>

i don't know why it is not working for me?
or is this is one of the cases in which replace method fails to remove whitespaces from the string?

Community
  • 1
  • 1
Sanmveg saini
  • 744
  • 1
  • 7
  • 22

4 Answers4

1

Try with regex by passing \g global modifier:

function s(){
  var ctr = " #d1 {       width: 100px ; height: 100px ; background-color: #000 ; opacity: 1 ; margin-left : 0px ; } ";            
  
  ctr = ctr.replace(/\s/g, ""); // \s means whitespace      
  alert(ctr);
}
<button onclick="s()">click</button>
Dev01
  • 4,082
  • 5
  • 29
  • 45
1

replace() only replaces the first occurrence. Here's one way to replace all occurrences:

How to replace all occurrences of a string in JavaScript?

Community
  • 1
  • 1
1

The answer is no...

Try:

function s(){
var str = " sanm sai s dj  k df  ";
str = String(str).replace(" ", "");
  
  alert(str);
  }
<button onclick="s();">click </button>
Sanmveg saini
  • 744
  • 1
  • 7
  • 22
lem2802
  • 1,152
  • 7
  • 18
0

A very simple answer would be to use:

stringName.replace(/ /g, "")

This will replace all occurrences of spaces. All spaces, however, are not strictly all of the whitespace, so for all whitespace you could alternatively use:

stringName.replace(/\s/g, "")
Ethan Humphries
  • 1,786
  • 3
  • 19
  • 28