最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Find length of string without counting included html tags - Stack Overflow

programmeradmin5浏览0评论

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.

Share Improve this question edited Oct 15, 2018 at 12:46 Daniel Beck 21.5k5 gold badges43 silver badges60 bronze badges asked Oct 15, 2018 at 12:34 Sai Saagar SharmanSai Saagar Sharman 1322 silver badges13 bronze badges 8
  • 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
 |  Show 3 more ments

2 Answers 2

Reset to default 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);

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

发布评论

评论列表(0)

  1. 暂无评论