0
<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to locate where in the string a specifed value occurs.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var a =" picture";
a.replace(" ","");


var n=a.indexOf(" ");
document.getElementById("demo").innerHTML= n+a+n;
}
</script>

</body>
</html>

I would like to replace " "(Space) out from the " picture" in the example above

but the result seem it's not replace by the replace command.

The result should be "-1picture-1" after replace but it's "0 picture0"

with a space in front of picture. (I use .indexOf(" ") to indicate that

there are a space in the variable or not -1 mean it doesn't )

What's it happen?? Please advise

Jongz Puangput
  • 5,527
  • 10
  • 58
  • 96

4 Answers4

9

replace doesn't modify the string in place, it returns a modified string.

a = a.replace(" ","");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Use String.trim() to remove trailing spaces.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim

In your example,

var a = " picture";
a = a.trim();
...
ddavison
  • 28,221
  • 15
  • 85
  • 110
  • 2
    This could be used if the OP doesn't need to support IE 8 … but since it also *returns* the modified value instead of operating in place, it doesn't solve the problem. (Although the additional, unexplained, changes you made in your example would) – Quentin Apr 25 '13 at 14:40
1

I think this could works pretty well...

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

why I got a downvote???

alert("some #$%%&& person gave me a downvote!!".replace(/\s+/g, ''));

this totally works!!!!!!

http://jsfiddle.net/ncubica/FBxy2/

ncubica
  • 8,169
  • 9
  • 54
  • 72
0

You need to assign the returned value back to a

var a =" picture";
a = a.replace(" ","");

edit:

Would also like to throw it out there that a .replace(" ","") will only work for the first instance of a space, and it may not even be at the beginning of the string. If you are wanting to trim only leading and trailing spaces, consider this:

var a =" picture";
a = a.replace(/^\s+|\s+$/g,"");
CrayonViolent
  • 32,111
  • 5
  • 56
  • 79