Sanmveg saini Sanmveg saini - 1 month ago 5
Javascript Question

Is there any case in which replace method fails to remove white space from the string?

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?

Answer

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

Replacing all occurrences of a string in JavaScript

Comments