假设我们有一个如下字符串:
,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将其转换为以下字符串?
34,23,4,5,634,12,3,1234,54,123,43,2,3424,45,56
实际上,我想删除重复的项目,并且首先和最后,
字符
答案 0 :(得分:4)
[已编辑]要将这些转换为一组唯一数字,就像您实际要求的那样,请执行以下操作:
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()
原语,您可以将其写成一行:
yourString.match(/\d+/g).map(parseBase10).unique()
不幸的是,由于这个荒谬的难以追踪的错误,你需要有点冗长并定义自己的parseBase10 = function(n){return parseInt(n)}
:javascript - Array#map and parseInt
答案 1 :(得分:1)
不需要正则表达式。几点招数
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);
如果你比jQuery更熟悉
text = text.replace(/,+/g, ',');
text = $.trim(text);
text = $.unique(text.split(",")).filter(function(e){ return e.length}).join(",");
console.log(text);
答案 2 :(得分:0)
这样做:
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));
这是jsFiddle
注意:我为更好的browser support
创建了自定义array.indexOf
函数