admin管理员组

文章数量:1425690

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

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

Share Improve this question edited Mar 31, 2012 at 23:09 ninjagecko 91.2k24 gold badges143 silver badges153 bronze badges asked Mar 31, 2012 at 22:48 Mohammad DayyanMohammad Dayyan 22.5k44 gold badges172 silver badges241 bronze badges 5
  • 3 uh, where'd the "34" go? – Samuel Edwin Ward Commented Mar 31, 2012 at 22:50
  • @SamuelEdwinWard it must have jumped overboard XD anyways, i think RegExp is not the tool for this job. i think you should parse it instead. – Joseph Commented Mar 31, 2012 at 22:51
  • I agree that it's not the right tool for the job; something starting with the "split" method on strings is probably the way to go. – Samuel Edwin Ward Commented Mar 31, 2012 at 22:53
  • You cannot remove the duplicate numbers solely with a regular expression. – Pointy Commented Mar 31, 2012 at 23:02
  • @Samuel Edwin Ward : I forgot it ;) – Mohammad Dayyan Commented Mar 31, 2012 at 23:05
Add a ment  | 

3 Answers 3

Reset to default 5

[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

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 mas with one ma
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(','); //bine 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

This will do it:

function arrIndex(fnd, arr) {
    for (var len = arr.length, i = 0; i < len; i++) {
        if (i in arr && arr[i] === fnd) {
            return i;
        }
    }
    return -1;
}

function scrapeNumbers(str) {
    var arr = str.replace(/,+/g, ",").replace(/^,/, "").replace(/,$/, "").split(",");

    for (var i = 0, len = arr.length, rtn = []; i < len; i++) {
        if (i in arr && arrIndex(arr[i], rtn) == -1) {
            rtn.push(arr[i]);
        }
    }
    return rtn.join(",");
}

var str = ",,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56,,";

alert(scrapeNumbers(str));

Here is a jsFiddle

Note: I created a custom array.indexOf function for a better browser support

本文标签: