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>

我想将上面示例中的“图片”中的“”(空格)替换掉

但结果似乎它没有被替换命令替换。

替换后的结果应该是“-1picture-1”,但它是“0 picture0”

图片前面有一个空格。(我使用 .indexOf(" ") 来表示

变量中是否有空格 -1 表示没有)

这是怎么回事??请指教

4

4 回答 4

9

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

a = a.replace(" ","");
于 2013-04-25T14:38:47.007 回答
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();
...
于 2013-04-25T14:39:17.687 回答
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,"");
于 2013-04-25T14:39:33.803 回答
0

我认为这可以很好地工作......

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

为什么我投了反对票???

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

这完全有效!!!!!!!

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

于 2013-04-25T14:41:10.750 回答