I have a paragraph which has HTML tags in it. I need to restrict it to 100 characters after the parse of HTML. For example
Hello<a href ="#"> World </a>
If my length check is for 8, then my HTML should be Hello Wo
where Wo
should be an anchor tag. There can be any other tags. Any help would be appreciated.
I have a paragraph which has HTML tags in it. I need to restrict it to 100 characters after the parse of HTML. For example
Hello<a href ="#"> World </a>
If my length check is for 8, then my HTML should be Hello Wo
where Wo
should be an anchor tag. There can be any other tags. Any help would be appreciated.
- what if you have already more than <limit> characters before your link? – Fabrizio Calderan Commented Oct 15, 2018 at 12:38
- 1 Maybe this post stackoverflow./questions/822452/… might help. It talks about how to remove HTML from a text, so you can count the other characters – Sorix Commented Oct 15, 2018 at 12:38
- break there it self, in the above example if the limit is 5, the output would be "hello" – Sai Saagar Sharman Commented Oct 15, 2018 at 12:39
- so your link would be promised but you asked to not lose elements. – Fabrizio Calderan Commented Oct 15, 2018 at 12:40
- Actually, the paragraph will be followed by show more and show less link, where i ll be showing the whole thing again. – Sai Saagar Sharman Commented Oct 15, 2018 at 12:41
2 Answers
Reset to default 6You can use a REGEX expresion when getting the innerHTML
Then count the characters.
Example:
var regex = /(<([^>]+)>)/ig;
var body = 'Hello<a href ="#"> World </a>';
var result = body.replace(regex, "");
console.log(result + ' ' + result.length);
$(document).ready(function(){
var $html=$('<span></span>');
$html.append('Hello<a href ="#"> World </a>');
var text=$html.text();
console.log("Text :: "+text);
console.log("Length :: "+text.length);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using this way you can create html elment virtually then text()
will parse the text content from html.