views:

3043

answers:

4

original string is "a,d,k" I want to remove all "," and make it to "adk". I tried: "a,d,k".replace(/,/,"") but it doesn't work. Thanks in advance.

+2  A: 

str.replace(",","")

le dorfier
thanks for quick reply, but I tried replace() and it doesn't work.
jiaoziren
+4  A: 

Use String.replace(), e.g.

var str = "a,d,k";
str = str.replace( /,/g, "" );

Note the g (global) flag on the regular expression, which matches all instances of ",".

Rob
A: 

You can try something like:

var str = "a,d,k";
str.replace(/,/g, "");
Paulo Santos
+7  A: 

You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

<html><head></head><body>
    <script type="text/javascript">
        var str1 = "a,d,k";
        str1.replace(/\,/g,"");
        var str2 = str1.replace(/\,/g,"");
        alert (str1);
        alert (str2);
    </script>
</body></html>

In this case, str1 will still be "a,d,k" and str2 will be "adk".

If you want to change str1, you should be doing:

var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");
Bob
thanks a lot. Thank you all.
jiaoziren
+1, but you can just do var str2; str2 = str.replace(...). I've expanded on the answer to (hopefully) improve it.
paxdiablo