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

javascript - How can I show only first x characters from a HTML code counting without tags - Stack Overflow

programmeradmin0浏览0评论

I use a text editor that will generate a html code and I save in database that html code. On another page I want to display first 100 characters only, but I don't want to count the html tags.

For example I have this html code saved in db:

<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to strip to 100 characters</span></p>
<p>Can be splited <b>between</b> multiple divs. 
Here is some more text to be longer <p>

If I substring as usual in javascript it will produce something like this:

<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to s

And this also broke the html code.

What I want is to have like this:

<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to strip to 100 characters</span></p>
<p>Can be splited <b>between</b> multiple divs. 
H<p>

I am using angular 4 for this project. So any idea using JS, angular, CSS, HTML or on the backend I have node.js will be helpfull.

I use a text editor that will generate a html code and I save in database that html code. On another page I want to display first 100 characters only, but I don't want to count the html tags.

For example I have this html code saved in db:

<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to strip to 100 characters</span></p>
<p>Can be splited <b>between</b> multiple divs. 
Here is some more text to be longer <p>

If I substring as usual in javascript it will produce something like this:

<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to s

And this also broke the html code.

What I want is to have like this:

<p><span style="color:red; font-size:20px; font-family:Arial">
Here is the real text that I want to strip to 100 characters</span></p>
<p>Can be splited <b>between</b> multiple divs. 
H<p>

I am using angular 4 for this project. So any idea using JS, angular, CSS, HTML or on the backend I have node.js will be helpfull.

Share Improve this question asked Apr 28, 2017 at 7:32 Daniel DudasDaniel Dudas 3,0023 gold badges28 silver badges41 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

On the frontend, you can do somethign like that :

var div=document.createElement("div");
div.innerHTML='<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>';
var excerpt=div.innerText.substring(0,100);
console.log(excerpt)

Where excerpt are the 100 first characters.

Edit if you want to keep the html tags check this:

var count = 0;

function strip(el, max) {
  var children = Array.prototype.slice.call(el.childNodes);
  children.forEach((node) => {
    if (node instanceof Text) {
      var newCount = count + node.textContent.length;
      var diff = newCount - max;
      if (diff > 0)
        node.textContent = node.textContent.substring(0, node.textContent.length - diff);
      count += node.textContent.length;
    } else if (node instanceof HTMLElement) {
      if (count >= max)
        node.remove(); // remove unnecessary tags
      else
        strip(node, max); // do recursively
    }
  })
}

var div = document.createElement("div");
div.innerHTML = '<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>'
var clone = div.cloneNode(true)
strip(clone, 100)
document.write("<h2>Original</h2>");
document.write(div.innerHTML);
document.write("<h2>Stripped</h2>");
document.write(clone.innerHTML);

Note that the strip function will modify an existing HTMLElement, that's why I cloned it.

If you want to do this on the server side, you can use a dom parser for nodejs and use the same approach.

You can use htmlToText in node

var htmlToText = require('html-to-text');
var htmlText = '<p><span style="color:red; font-size:20px; font-
   family:Arial">Here is the real text that I want to strip to 100 characters</span></p>
   <p>Can be splited <b>between</b> multiple divs. 
   Here is some more text to be longer <p>';

var text_100firstNonHtml  = htmlToText.fromString(htmlText, {
    wordwrap: 130
}).substring(0,100);


console.log(text_100firstNonHtml);

You say your backend is nodejs, so the best and easiest could be that if you strip out all the html tags in server side and sending only the text to the client with a desired lenght. Check out the "striptags" npm package for node. https://www.npmjs./package/striptags

Or with jQuery it is quite easy (can be either on server or client side) but you can use any html parser/framework

var htmlStr = '<p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 100 characters aaaaa bbbbbb cccccc ddddd eeeeee ffff ggggg hhhh iiii jjjj kkk llllll mmmm nnnn</span></p><p>Can be splited <b>between</b> multiple divs. Here is some more text to be longer <p>';
var $html = $(htmlStr);

$html.find('*').each(function(idx, tag) {
  var shortText = $(tag).text().substring(0,100);
  $(tag).text(shortText);
});

console.log($html.html());
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Iterate all children text, mark the x-character spot with a unique string (like '@@' in my demo) and then keep the inner html up to that point (I used a 70-char limit for test purpose):

var counter = 0;
var children = document.getElementById("test").children;
for (var i = 0; i < children.length; i++) {
  var node = children[i];
  var inText = node.textContent;
  if (counter + inText.length > 70) {
    var index = 70 - counter;
    node.textContent = inText.slice(0, index) + "@@" + inText.slice(index);
    break;
  } else {
    counter += inText.length;
  }
}
var index = document.getElementById("test").innerHTML.indexOf("@@");
var output = document.getElementById("test").innerHTML.substring(0,index);
alert(output);
<div id="test">
  <p><span style="color:red; font-size:20px; font-family:Arial">Here is the real text that I want to strip to 70 characters</span></p>
  <p>Can be splited <b>between</b> multiple divs.H
    <p>
</div>

(you may also want to remove the @@ mark after that)

if you need to render API response in html file, then u can use

{{response.string.slice(0,100)}}

It will display only first 100 characters from your string.
发布评论

评论列表(0)

  1. 暂无评论