使用Javascript中的RegExp在开始/结束时删除重复的逗号和额外的逗号,并删除重复的数字? [英] Remove duplicate commas and extra commas at start/end with RegExp in Javascript, and remove duplicate numbers?

查看:109
本文介绍了使用Javascript中的RegExp在开始/结束时删除重复的逗号和额外的逗号,并删除重复的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个如下字符串:

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

如何在Javascript中使用RegExp将其转换为以下字符串?

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

实际上,我想删除重复的项目,并且首先和最后 char

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

推荐答案

要将这些变为一组唯一数字,正如您实际要求的那样,请执行以下操作:

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

演示:

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

如果您有一个 Array.prototype.unique()原语,您可以将它写成一行:

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

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

不幸的是你需要有点冗长并定义你自己的 parseBase10 = function(n){return parseInt(n) } 由于这个荒谬的难以追踪的错误: javascript - Array#map和parseInt

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

这篇关于使用Javascript中的RegExp在开始/结束时删除重复的逗号和额外的逗号,并删除重复的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆