Athapali
Athapali

Reputation: 1089

regex to extract html comment attribute

I have a table cell with the following comment:

 <!-- FieldName="Predicted Process Equipment Potable Usage"
             FieldInternalName="PredictedProcessEquipmentPotable"
             FieldType="SPFieldNumber" -->

There are many table cells with similar pattern comments, where the values of the attribute differ, but the attributes are always the same (FieldName, FieldInternalName, and FieldType).

How do I extract using REGEX the FieldInternalname in this type of comment? Is there a non-regex way of doing it too?

Please help!

Upvotes: 0

Views: 75

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

Use the below regex and get the value of FieldInternalName from group index 1.

<!--[\S\s]*?FieldInternalName="([^"]*)"[\S\s]*?-->

DEMO

> var m = 'foo\n <!-- FieldName="Predicted Process Equipment Potable Usage"\n            FieldInternalName="PredictedProcessEquipmentPotable"\n           FieldType="SPFieldNumber" -->';
undefined
> console.log(/<!--[\S\s]*?FieldInternalName="([^"]*)"[\S\s]*?-->/.exec(m)[1]);
PredictedProcessEquipmentPotable

Upvotes: 2

Paul S.
Paul S.

Reputation: 66334

Is there a non-regex way of doing it too?

commentNode.data;

Comment nodes have nodeType of 8, so if you don't know which child of the cell it will be, you can write a function like this

function getNodesByType(node, type, childrenOnly) {
    var i,
        o = [];
    if (node.childNodes && node.childNodes.length)
        for (i = 0; i < node.childNodes.length; ++i)
            if (node.childNodes[i].nodeType === type)
                o.push(node.childNodes[i]);
            else if (!childrenOnly && node.childNodes[i].nodeType === 1)
                Array.prototype.push.apply(
                    o,
                    getNodesByType(node.childNodes[i], type, childrenOnly)
                );
    return o;
}

And invoke getNodesByType(yourTdElement, 8, true); to get an Array of comment nodes which are immediate children of your <td>

Upvotes: 1

Related Questions