Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove "," from a string in javascript

original string is "a,d,k" I want to remove all , and make it to "adk".

I tried code below but it doesn't work.

"a,d,k".replace(/,/,"")
like image 495
jiaoziren Avatar asked May 26 '09 01:05

jiaoziren


People also ask

How do I remove a specific character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do you remove part of a string?

You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.


3 Answers

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, ""); 
like image 101
Bob Avatar answered Sep 20 '22 04:09

Bob


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 ",".

like image 28
Rob Avatar answered Sep 21 '22 04:09

Rob


You can try something like:

var str = "a,d,k";
str.replace(/,/g, "");
like image 21
Paulo Santos Avatar answered Sep 19 '22 04:09

Paulo Santos