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(/,/,"")
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.
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.
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, "");
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 ",".
You can try something like:
var str = "a,d,k";
str.replace(/,/g, "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With