how to remove "," from a string in javascript
JavascriptStringJavascript Problem Overview
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(/,/,"")
Javascript Solutions
Solution 1 - Javascript
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, "");
Solution 2 - Javascript
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 ",".
Solution 3 - Javascript
You can try something like:
var str = "a,d,k";
str.replace(/,/g, "");
Solution 4 - Javascript
If U want to delete more than one characters, say comma and dots you can write
<script type="text/javascript">
var mystring = "It,is,a,test.string,of.mine"
mystring = mystring.replace(/[,.]/g , '');
alert( mystring);
</script>
Solution 5 - Javascript
<script type="text/javascript">var s = '/Controller/Action#11112';if(typeof s == 'string' && /\?*/.test(s)){s = s.replace(/\#.*/gi,'');}document.write(s);</script>
It's more common answer. And can be use with s= document.location.href;
Solution 6 - Javascript
If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.
Here the 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;
}
Modify that for loop if you need bigger numbers.