Javascript正则表达式括号内的子匹配数组

时间:2018-04-27 18:55:47

标签: javascript

是否可以将子匹配作为数组而不是参数?

像这样:

text.replace(/^(?!(^$)|\<(h[0-9])\>)(.*)$/mg, function(match, submatches) {
    return '<p>'+submatches[2]+'</p>';
});

而不是:

text.replace(/^(?!(^$)|\<(h[0-9])\>)(.*)$/mg, function(match, p1, p2, p3) {
    return '<p>'+p3+'</p>';
});

2 个答案:

答案 0 :(得分:2)

您可以使用rest运算符将所有参数聚合到单个参数数组中:

 Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
    'Adds an item to the checkbox list when making a sale
    Dim ItemID As Integer = txtSalesProductID.Text
    Dim rowNum As Integer = (Group16DataSet1.Product.Rows.Count) - 1

    Dim valid As Boolean = False


    For value As Integer = 0 To rowNum
        If (ItemID = Group16DataSet1.Product.Rows(value).Item(0)) Then
            valid = True

            If (temp.Contains(ItemID.ToString)) Then
                MsgBox("AGAIN")

                For i As Integer = 0 To c - 1
                    If (arrProductID(i) = ItemID) Then
                        productList.Items.RemoveAt(i + 2)
                        arrProduct(i) += 1
                        productList.Items.Add(String.Format(stringP, Group16DataSet1.Product.Rows(i).Item(1).ToString, arrProduct(i), "R " + Group16DataSet1.Product.Rows(i).Item(4).ToString))
                        MsgBox(i)
                    End If
                Next

            Else
                MsgBox("ENTERED ONCE")
                temp = temp + "," + Group16DataSet1.Product.Rows(value).Item(0).ToString

                ReDim arrProductID(100)
                ReDim Preserve arrProductID(c)
                arrProductID(c) = 1

                ReDim arrProduct(100)
                ReDim Preserve arrProduct(c)
                arrProduct(c) = 1

                productList.Items.Add(String.Format(stringP, Group16DataSet1.Product.Rows(value).Item(1).ToString, arrProduct(c), "R " + Group16DataSet1.Product.Rows(value).Item(4).ToString))

                c += 1
            End If
        End If

    Next

    If valid = False Then
        MsgBox("Product not in stock")
    End If

    For i As Integer = 0 To (productList.Items.Count - 1)
        '  ProductList.SetItemChecked(i, True)
    Next
End Sub

答案 1 :(得分:2)

Javascript有一个特殊的对象,它被传递给每个名为arguments的函数调用。

function(match) {
    var submatches = Array.prototype.slice.call(arguments, 1);
}

这适用于旧版本的Javascript,而rest parameter运算符仅适用于ES6。