0

I want to assign HTML snippet to string variable. something like -

 string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello'

Please suggest.

Tyler Lee
  • 2,736
  • 13
  • 24
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
  • 9
    First someone will propose regex. Then that person will be murdered. Then someone will post a link to HtmlAgilityPack. – Jon B Nov 02 '12 at 14:41
  • I don't see the question? You seem to have successfully put HTML into a string. How are you using the string? – Tyler Lee Nov 02 '12 at 14:41
  • At the risk of being murdered, this is similar to http://stackoverflow.com/questions/787932/using-c-sharp-regular-expressions-to-remove-html-tags – McArthey Nov 02 '12 at 14:47
  • Where are you getting the HTML from? It might be easier to just pull out the text there. – Bobson Nov 02 '12 at 14:48
  • http://mattgemmell.com/2008/12/08/what-have-you-tried/ – Matthias Meid Nov 02 '12 at 14:49

2 Answers2

1

If you are sure that the HTML won't change between the string you want to get, you can simply do a Substring between the two constants string and you will get your string into your variable.

        const string prefix = "<table>";
        const string suffix = "</table>";
        string s = prefix + "TEST" + suffix ;
        string s2 = s.Substring(prefix.Length, s.IndexOf(suffix, StringComparison.Ordinal) - prefix.Length);

Here is the Regex version:

        const string prefix = "<table>";
        const string suffix = "</table>";
        string s = prefix + "TEST" + suffix;
        string s2 = Regex.Match(s, prefix + "(.*)" + suffix).Groups[1].Value;
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
1
        string div = "<table><tr><td>Hello</td></tr></table>"; // It should return only 'Hello

        var doc = new XmlDocument();
        doc.LoadXml(div);
        string text = doc.InnerText;

Do you also need the Jquery version of this?

C.M.
  • 1,474
  • 13
  • 16