Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...