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?
var string = "Hi";
alert(string.substr(0, 7));
Alert:
Hi
var string = "<br/>Hi";
alert(string.substr(0, 7));
Alert:
<br/>Hi
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With