Showing posts with label InnerText. Show all posts
Showing posts with label InnerText. Show all posts

Wednesday, July 31, 2013

Replacement of InnerText property, while updating display text of elements such as (span, etc) in HTML.

This article aims to provide a javascript function to update display text of controls such as (SPAN, etc) in HTML using javascript. 

Generally, we tend to update innerText  property of such elements in this scenario, but when it works perfectly as expected in IE and Chrome, it fails in Firefox. Because,it's not supported.

Instead, include below javascript function in your JS library, and call it. This is more elegant and cross-browser solution of this problem.



function setTextContent(element, text) {
    while (element.firstChild!==null)
        element.removeChild(element.firstChild); // remove all existing content
    element.appendChild(document.createTextNode(text));
}


Sample call:

setTextContent($('span.displayText), result);

Monday, May 21, 2012

Remove HTML tags from a text string in ASP.NET using RegularExpression

This article aims to explain a very simple method to remove HTML tags from a text using RegularExpressions.

This will remove all HTML tags, or character references (like, &nbsp, &amp) from a text, and will return plain text.

    public static string RemoveHtmlTags(string htmlText, bool preserveNewLine)
    {
        System.Web.UI.HtmlControls.HtmlGenericControl divNew = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
        divNew.InnerHtml = htmlText;
        if (preserveNewLine)
        {
            divNew.InnerHtml = divNew.InnerHtml.Replace("<br>", "\n");
            divNew.InnerHtml = divNew.InnerHtml.Replace("<br/>", "\n");
            divNew.InnerHtml = divNew.InnerHtml.Replace("<br />", "\n");
        }
        return System.Text.RegularExpressions.Regex.Replace(divNew.InnerText, "<[^>]*>", "");
    }

if there is a requirement to preserve new line, then we need to convert HTML line breaks into new line character (which is "\n" in C#).

Example output using above method:
Input: &nbsp;Take one <strong>notebook</strong>, pen, <u>pencil</u> and <em>eraser</em> with you.
Result:  Take one notebook, pen, pencil and eraser with you.
(In above example, &nbsp; is replaced by a space character in the beginning)