how to remove “,” from a string in javascript

后端 未结 6 481
我在风中等你
我在风中等你 2020-12-24 00:03

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.

相关标签:
6条回答
  • 2020-12-24 00:38

    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.

    0 讨论(0)
  • 2020-12-24 00:43

    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, "");
    
    0 讨论(0)
  • 2020-12-24 00:47

    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>
    
    0 讨论(0)
  • 2020-12-24 00:47

    <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;

    0 讨论(0)
  • 2020-12-24 00:54

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

    0 讨论(0)
  • 2020-12-24 00:54

    You can try something like:

    var str = "a,d,k";
    str.replace(/,/g, "");
    
    0 讨论(0)
提交回复
热议问题