Var stripedHtml = htmlString.replace(/] >/g, '') If you're working in a Node environment, where there's not either document or createElement method, then you can use a regular expression to replace all the HTML tags from a string: var htmlString= "Hello World\nIt's me, Mario" Var stripedHtml = $("").html(htmlString).text() Ĭonsole.log(stripedHtml) 3. The following code will do the same that the code in the first step (the warnings apply too): var htmlString= "\n Hello World\n This is the text that we should get.\n Our Code World © 2017\n " If you use jQuery you can simplificate the code from the first step. Therefore, you should use this only if you trust the source of the HTML string. The only problem of this (and the advantage) is that the browser will handle the providen string as HTML, that means that if the HTML string contains some type of interpretable Javascript for the browser, then it will be executed: // This won't do anything but retrieve the text Var htmlString= "Hello World\nIt's me, Mario" Return temporalDivElement.textContent || temporalDivElement.innerText || "" Retrieve the text property of the element (cross-browser support) Set the HTML content with the providen Var temporalDivElement = document.createElement("div") The content of a temporary div element, will be the providen HTML string to strip, then from the div element return the innerText property: /** This is the preferred (and recommended) way to strip the HTML from a string with Javascript. Create a temporary DOM element and retrieve the text In this article, you will find 3 ways to strip the html tags from a string in Javascript. However, if you're unable to use the server (or you use Node.js) to achieve this task, then you can still use Javascript to do it. Normally in the server side you could use a series of PHP functions (such as strip_tags) and to remove HTML and ugly formatting.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |