Search code examples
asp.netvb.netsubstrlastindexof

Inserting text before the second last instance of an element in a string VB.net


I've got a document like the following layout (in reality it's much bigger):

<div id="header">
    <div id="whatever">
        <div id="content">
            <p>Yes</p>
        </div>
    </div>
</div>

I'm importing that html from elsewhere and I don't have control over it. I need to add an extra bit of html before the second last div: i.e.

<div id="header">
    <div id="whatever">
        <div id="content">
            <p>Yes</p>
        </div>

        [In here!]

    </div>
</div>

Now I've got part of the way there using substr and lastindexof..but I can't quite work out how to get to the div before.

Here is what I have:

Public Partial Class RightMenuControl
    Inherits System.Web.UI.UserControl

    Private dtItemsFeed As dsItems.ItemsFeedDataTable
    Private taItemsFeed As New dsItemsTableAdapters.ItemsFeedTableAdapter
    Private allText As String


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        loadData()
    End Sub

    Private Sub loadData()

        dtItemsFeed = New dsItems.ItemsFeedDataTable
        dtItemsFeed = taItemsFeed.GetCode()

        For Each rFeed As dsItems.ItemsFeedRow In dtItemsFeed
            allText = rFeed.SideCode
        Next

        Dim FirstDiv As String = allText.LastIndexOf("</div>")
        Dim LastDiv As String = allText.Substring(FirstDiv, 6)

        Dim str As String = allText

        Dim strRes As String = str.Insert(FirstDiv, "<div>extrahtml</div>")

        ltrSide.Text = strRes


    End Sub
End Class

Which prints my extrahtml div in:

<div id="header">
    <div id="whatever">
        <div id="content">
            <p>Yes</p>
        </div>
    </div>
        <div>extrahtml</div> 
</div>

Tom


Solution

  • Ok, knowing that it will always be the second to last Div, this should do the trick.

    Dim LastDiv As Int = allText.LastIndexOf( "</div>" )
    Dim SecondToLastDiv As Int = allText.LastIndexOf( "</div>", LastDiv ) - 1
    
    Dim str As String = allText
    Dim strRes As String = str.Insert(SecondToLastDiv, "<div>extrahtml</div>")