我如何基于包含特定字符的对象字符串拆分数组?

问题描述 投票:-3回答:1

我目前有一个带有各种不同标签的数组,我希望能够根据数组中的对象是否包含特定字符来拆分该数组。

当前数组是这样的:

var tagArray = ["<div>", "<div class="extra">", "<h1>", "</h1>", "<h3>", "</h3>", "</div>", "<p>", "</p>", "</div>"]

我想做的就是创建一个函数,该函数可以根据字符串是否包含/字符将数组分成两个单独的数组

javascript arrays
1个回答
0
投票

因此,如果我理解正确,您想将tagArry拆分为2个新数组,其中一个包含所有包含/字符的字符串,另一个数组应该包含不带/字符的元素?如果确实是您要这样做,则使用filter方法相当简单。

    var tagArray = ['<div>', '<div class="extra">', "<h1>", "</h1>", "<h3>", "</h3>", "</div>", "<p>", "</p>", "</div>"];

    const arrWithSlashElements = tagArray.filter(e => e.includes('/'));
    console.log(arrWithSlashElements);

    const arrWithoutSlashElements = tagArray.filter(e => !e.includes('/'));
    console.log(arrWithSlashElements);
© www.soinside.com 2019 - 2024. All rights reserved.