开发者

replace keyword within html string

I am looking for a way to replace keywords within a html string with a variable. At the moment i am using the following example.

returnString = Replace(message, "[CustomerName]", customerName, CompareMethod.Text)

The above will work fine if the html block开发者_StackOverflow中文版 is spread fully across the keyword.

eg.

<b>[CustomerName]</b>

However if the formatting of the keyword is split throughout the word, the string is not found and thus not replaced.

e.g.

<b>[Customer</b>Name]

The formatting of the string is out of my control and isn't foolproof. With this in mind what is the best approach to find a keyword within a html string?


Try using Regex expression. Create your expressions here, I used this and it works well.

http://regex-test.com/validate/javascript/js_match


Use the text property instead of innerHTML if you're using javascript to access the content. That should remove all tags from the content, you give back a clean text representation of the customer's name.

For example, if the content looks like this:

<div id="name">
    <b>[Customer</b>Name]
</div>

Then accessing it's text property gives:

var name = document.getElementById("name").text;
// sets name to "[CustomerName]" without the tags

which should be easy to process. Do a regex search now if you need to.

Edit: Since you're doing this processing on the server-side, process the XML recursively and collect the text element's of each node. Since I'm not big on VB.Net, here's some pseudocode:

getNodeText(node) {
    text = ""
    for each node.children as child {
        if child.type == TextNode {
            text += child.text
        }
        else {
            text += getNodeText(child);
        }
    }
    return text
}

myXml = xml.load(<html>);
print getNodeText(myXml);

And then replace or whatever there is to be done!


I have found what I believe is a solution to this issue. Well in my scenario it is working.

The html input has been tweaked to place each custom field or keyword within a div with a set id. I have looped through all of the elements within the html string using mshtml and have set the inner text to the correct value when a match is found.

e.g.

Function ReplaceDetails(ByVal message As String, ByVal customerName As String) As String
    Dim returnString As String = String.Empty
    Dim doc As IHTMLDocument2 = New HTMLDocument
    doc.write(message)
    doc.close()
    For Each el As IHTMLElement In doc.body.all
        If (el.id = "Date") Then
            el.innerText = Now.ToShortDateString
        End If
        If (el.id = "CustomerName") Then
            el.innerText = customerName
        End If
    Next
    returnString = doc.body.innerHTML
    return returnString

Thanks for all of the input. I'm glad to have a solution to the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜