March 31, 2012

Remove duplicate commas and extra commas at start/end with RegExp in Javascript, and remove duplicate numbers?

Question by Mohammad

Assume we have a string like the following :

,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56

How can we convert it to the following string with RegExp in Javascript ?

34,23,4,5,634,12,3,1234,54,123,43,2,3424,45,56

Actually, I wanna remove repeated items and first and last , char

Answer by ninjagecko

[edited] To turn these into a set of unique numbers, as you are actually asking for, do this:

function scrapeNumbers(string) {
    var seen = {};
    var results = [];
    string.match(/d+/g).forEach(function(x) {
        if (seen[x]===undefined)
            results.push(parseInt(x));
        seen[x] = true;
    });
    return results;
}

Demo:

> scrapeNumbers(',1,22,333,22,,333,4,,,')
[1, 22, 333, 4]

If you had an Array.prototype.unique() primitive, you could write it like so in one line:

yourString.match(/d+/g).map(parseBase10).unique()

Unfortunately you need to be a bit verbose and define your own parseBase10 = function(n){return parseInt(n)} due to this ridiculous hard-to-track-down bug: javascript – Array.map and parseInt

Answer by Starx

No need for regex. Few tricks

text = ',34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56';
text = text.replace(/,+/g, ','); //replace two commas with one comma
text = text.replace(/^s+|s+$/g,''); //remove the spaces
textarray = text.split(","); // change them into array
textarray = textarray.filter(function(e){ return e.length});
console.log(textarray);                                       


// Now use a function to make the array unique
Array.prototype.unique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(this[i] in u)
         continue;
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

textarray = textarray.unique();
text = textarray.join(','); //combine them back to what you want
console.log(text);

Demo

If you are familier with jQuery

text = text.replace(/,+/g, ',');
text = $.trim(text);
text = $.unique(text.split(",")).filter(function(e){ return e.length}).join(",");
console.log(text);

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!