How to remove "," from a string in javascript

the source line is "a, d, k", I want to delete everything "," and make it "adk". I tried: "a, d, k" .replace (/, /, ""), but it does not work. Thanks in advance.

+61
javascript string
May 26 '09 at 1:46 a.m.
source share
6 answers

You do not assign the result of the replacement method back to your variable. When you call replace, it returns a new line without changing the old one.

For example, download 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 do:

 var str1 = "a,d,k"; str1 = str1.replace (/,/g, ""); 
+106
May 26 '09 at 1:53 a.m.
source share

Use String.replace() for example

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

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

+34
May 26 '09 at 1:49 a.m.
source share

You can try something like:

 var str = "a,d,k"; str.replace(/,/g, ""); 
+4
May 26 '09 at 1:50
source share

If U wants to delete more than one character, such as a comma and periods, you can write

 <script type="text/javascript"> var mystring = "It,is,a,test.string,of.mine" mystring = mystring.replace(/[,.]/g , ''); alert( mystring); </script> 
+4
Nov 13 '14 at 5:25
source share

<script type="text/javascript">var s = '/Controller/Action#11112';if(typeof s == 'string' && /\?*/.test(s)){s = s.replace(/\#.*/gi,'');}document.write(s);</script>

This is a more general answer. And can be used with s= document.location.href;

-2
Apr 22 2018-12-12T00:
source share

If you need a number in excess of 999,999.00, you will have a problem.
They are good only for numbers less than 1 million, 1,000,000.
They remove only 1 or 2 commas.

Here is a script that can remove up to 12 commas:

 function uncomma(x) { var string1 = x; for (y = 0; y < 12; y++) { string1 = string1.replace(/\,/g, ''); } return string1; } 

Change this for a loop if you need large numbers.

-3
Feb 20 '15 at 21:54
source share



All Articles