Adige72
Adige72

Reputation: 177

Multiple regex match in javascript

document.querySelectorAll("table[id^='Table']");

This code selects all tables with the id of Table. But i want to select tables with id of Table2 OR Table7 (or any other numbers). How to do this with regex?

Edit: jQuery is not applicable in my case.

Upvotes: 0

Views: 90

Answers (1)

11684
11684

Reputation: 7507

function getTables(tableNumbers) { // Usage: getTables([2, 7]) will return the tables with the ID 'Table2' and 'Table7'. (You can add more numbers; [2,7,3,6])
    var allTables = document.querySelectorAll("table[id^='Table']");
    var tablesWeWant = [];
    for (var i = 0; i < allTables.length; i++) {
        if (allTables[i].id.match(/Table[0-9]/)) {
            tablesWeWant.push(allTables[i]);
        }
    }
    for (var i = 0; i < tablesWeWant.length; i++) {
        if (!tableNumbers.contains(tablesWeWant[i].id.substr(id.length - 1))) {
            tableNumbers.splice(i, 1);
        }
    }
    return tablesWeWant;
}

This should return all tables with an ID matching the regex /Table[0-9]/ and ending with a digit contained in the variable tableNumbders.

DISCLAIMER: I'm not a regex expert.

EDIT:
After editing a few times the code above became a bit too long, so I rewrote it like this:

function getTables(tableNumbers) {
    var tablesWeWant = [];
    for (var i = 0; i < tableNumbers.length; i++) {
        tablesWeWant.push(document.querySelector("#Table" + tableNumbers[i]));
    }
    return tablesWeWant;
}

The second approach works: http://jsfiddle.net/qQ7VT/1/

Upvotes: 2

Related Questions