Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: parse HTML into text

I use substr() on a string to output a set of characters from a message. My problem is that if the string contains HTML I would get the tags in the text.

Is it possible to parse the HTML before using substr() to only extract the text from the message itself?

Example 1:

var string = "Hi";

alert(string.substr(0, 7));

Alert:

Hi


Example 2:

var string = "<br/>Hi";

alert(string.substr(0, 7));

Alert:

<br/>Hi

like image 397
Sam Pettersson Avatar asked Dec 19 '22 19:12

Sam Pettersson


2 Answers

Using jQuery.text() method, you can extract only the text.

var str = "<br/>Hi"

$('<p>' + str + '</p>').text(); //Wrap your input in a p element first to ensure you get the text if your string isn't wrapped in HTML.
like image 145
crush Avatar answered Jan 05 '23 08:01

crush


You can remove the html via a regex, see the answer here and you can do something like this:

String.prototype.removeHtml=function(){
  return this.replace(/(<([^>]+)>)/ig,"");
}

var string = "<br/>Hi";

alert(string.removeHtml().substr(0, 7));

Fiddle: http://jsfiddle.net/fx3MJ/

Remove HTML Tags in Javascript with Regex

like image 45
Hattan Shobokshi Avatar answered Jan 05 '23 08:01

Hattan Shobokshi