How to strip out only Text from HTML string using javascript?


Suppose I have an HTML string like below:

 <div style="margin-top:10px" data-href="/URL" data-Id="1">
     Some text here
 </div>

now what I need to do is get only Text part from the above HTML string, i.e. "Some text here", so how can I get only Text part from HTML string using javascript or jQuery?

Please Note: I have HTML string here, and It is not already in DOM, so I cannot get it HTML element using its class or Id in javascript and get Text.


Asked by:- bhanu
0
: 4052 At:- 1/19/2018 2:32:00 PM
javascript HTML strip HTML from a string







1 Answers
profileImage Answered by:- manish

You can use the following javascript code to extract only Text part from HTML string

function GetHtml(html){
    // Create a new div element
    var temporaryDivElement = document.createElement("div");
    // Set the HTML content with the providen
    temporaryDivElement.innerHTML = html;
    // Retrieve the text property of the element (cross-browser support)
    return temporaryDivElement.textContent || temporaryDivElement.innerText || "";
}

In the above method, we are creating a temporary div and then appending our given HTML string to it,after that we will Get inner text of html only.

So, you can use it like

function GetHtml(html){
    // Create a new div element
    var temporaryDivElement = document.createElement("div");
    // Set the HTML content with the providen
    temporaryDivElement.innerHTML = html;
    // Retrieve the text property of the element (cross-browser support)
    return temporaryDivElement.textContent || temporaryDivElement.innerText || "";
}

var htmlStr ='<div style="margin-top:10px" data-href="/URL" data-Id="1">Some text here</div>';

//Output : Some text here
console.log(GetHtml(htmlStr));

Using Jquery, we can do it in simpler way

var htmlString= "<div>\n <h1>Hello World</h1>\n <p>This is the text that we should get.</p>\n <p>Our Code World &#169; 2017</p>\n </div>";

var stripedHtml = $("<div>").html(htmlString).text();

// Hello World
// This is the text that we should get.
// Our Code World © 2017
console.log(stripedHtml);
1
At:- 1/20/2018 8:33:38 AM
thanks, I have tried only javascript solution which was needed 0
By : bhanu - at :- 1/26/2018 3:42:59 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use