Remove character from string using javascript

前端 未结 7 2150
失恋的感觉
失恋的感觉 2020-12-11 16:03

i have comma separated string like

var test = 1,3,4,5,6,

i want to remove particular character from this string using java script

can a

相关标签:
7条回答
  • 2020-12-11 16:47

    You can also

    var test1 = test.split(',');

    delete test1[2];

    var test2 = test1.toString();

    Have fun :)

    0 讨论(0)
  • 2020-12-11 16:50

    You can use this function

    function removeComma(inputNumber,char='') {
    
            return inputNumber.replace(/,/g, char);
        }
    

    Update

       function removeComma(inputNumber) {
            inputNumber = inputNumber.toString();
            return Number(inputNumber.replace(/,/g, ''));
        }
    
    0 讨论(0)
  • 2020-12-11 16:54
    var test = '1,3,4,5,6';​​
    
    //to remove character
    document.write(test.replace(/,/g, '')); 
    
    //to remove number
    function removeNum(string, val){
       var arr = string.split(',');
       for(var i in arr){
          if(arr[i] == val){
             arr.splice(i, 1);
             i--;
          }
      }            
     return arr.join(',');
    }
    
    var str = removeNum(test,3);    
    document.write(str); // output 1,4,5,6
    
    0 讨论(0)
  • 2020-12-11 16:56

    you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again

      

    // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };
    

    0 讨论(0)
  • 2020-12-11 17:01

    Use replace and if you want to remove multiple occurrence of the character use

    replace like this

    var test = "1,3,4,5,6,";
    var newTest = test.replace(/,/g, '-');
    

    here newTest will became "1-3-4-5-6-"

    0 讨论(0)
  • 2020-12-11 17:04

    JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.

    Example:

    var str = 'aba';
    str.replace('a', ''); // results in 'ba'
    str.replace(/a/g, ''); // results in 'b'
    

    If you alert str - you will get back the same original string cause strings are immutable. You will need to assign it back to the string :

    str = str.replace('a', '');
    
    0 讨论(0)
提交回复
热议问题