Javascript 数组对象用正则表达式替换数据

Javascript array object replace data with regexp

本文关键字:替换 数据 正则表达式 数组 对象 Javascript      更新时间:2023-09-26

我有这样的对象数组:

test = [",postContent", ",All", ",true", ",270", ",360", ",true", ",true", 
        ",true", ",undefined", ",undefined", ",undefined", ",undefined",
        ",true", ",true", ",302612", ",2668", ",185", ",292", ",6433",
        ",1846", ",843", ",3272", ",4458", ",2069", ",642", ",20", ",5",
        ",25", ",20", ",6", ",101", ",19", ",66", ",44", ",true", ",true",
        ",true", ",true", ",true", ",true", ",true", ""];

如您所见,它是对象数组,我无法使用test.replace(regexp)

在这种情况下,如何用对象数组替换"后的所有逗号?

您可以使用Array.prototype.map

test = test.map(function(item){
    return item.replace(/^,/, '');
});

或者,假设所有条目都以 , 开头或都是空字符串,这应该更快

test = test.map(function(item){
    return item.substr(1);
});

这将做到这一点:

test = test.join("-").replace(",","").split("-");

请记住,您的文本不得包含"-"字符才能正常工作。您可以将两个"-"替换为足够复杂的分隔符变量。

test.join("-") 将数组测试转换为字符串",postContent-,All-,true...".replace(",","") 将字符串中的逗号替换为空字符,因此字符串将被"postContent-All-true...",最后.split("-")会将最后一个字符串转换为数组["postContent", "All", "true", ...]从而产生所需的输出。