1

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.

8
  • what if you have already more than <limit> characters before your link? Commented Oct 15, 2018 at 12:38
  • 1
    Maybe this post stackoverflow.com/questions/822452/… might help. It talks about how to remove HTML from a text, so you can count the other characters 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" Commented Oct 15, 2018 at 12:39
  • so your link would be compromised but you asked to not lose elements. 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. Commented Oct 15, 2018 at 12:41

2 Answers 2

6

You 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);

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, where do i pass the length.
Use the result.length in your validating function
This will work great until you run into an attribute containing either the "<" or ">" characters...
1

$(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.com/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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.