Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Extract text from a string without jQuery

I have this string:

var string = '<article><img alt="Ice-cream" src=http://placehold.it/300x300g"><div style="float: right; width: 50px;"><p>Lorem Ipsum </p></div></article>';

and I am trying to extract the text out of it as such:

var $str = $(string).text();
console.log($str)

but since I am concerned about performance due to a huge amount of strings with big text, I would want to go natively.

How is this possible?

like image 829
jQuerybeast Avatar asked Jul 21 '13 20:07

jQuerybeast


2 Answers

Let the Browser do the sanitation and use this trick:

var str= '<article><img alt="Ice-cream" src=http://placehold.it/300x300g">'+
'<divstyle="float: right; width: 50px;"><p>Lorem Ipsum </p></div></article>';

var dummyNode = document.createElement('div'),
    resultText = '';

dummyNode.innerHTML = str;
resultText = dummyNode.innerText || dummyNode.textContent;

This creates a dummy DOM element and sets its HTML content to the input string.
Now the only text can be got by simply calling the DOM property innerText or textContent.

This is also more safe and robust as Browser has already written better algorithms to get these values.

like image 154
Om Shankar Avatar answered Nov 15 '22 23:11

Om Shankar


You have to make global search to find any characters any no. of time between < and >

<script type="text/javascript">

var str='<article><img alt="Ice-cream" src=http://placehold.it/300x300g"><div style="float: right; width: 50px;"><p>Lorem Ipsum </p></div></article>';
var patt=/\<.*?\>/g;

var result = str.replace(patt, "");
console.log(result);

</script>
like image 26
Premshankar Tiwari Avatar answered Nov 15 '22 22:11

Premshankar Tiwari