12

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 anyone suggests me?

3
  • 3
    What is your expected result? Commented Nov 9, 2012 at 6:54
  • you want to remove the separator or some number in your string? What do you want to output: an array or a string? Commented Nov 9, 2012 at 6:55
  • Possible duplicate of Javascript - remove character from a string Commented Nov 22, 2016 at 11:17

7 Answers 7

42

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', '');
Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

4

you can make use of JavaScript replace() Method

var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");

Comments

1
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

Comments

1

You can also

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

delete test1[2];

var test2 = test1.toString();

Have fun :)

Comments

0

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

Comments

0

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, ''));
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.