使用 JavaScript 从 HTML 字符串中提取文本 [英] Extract the text out of HTML string using JavaScript

查看:49
本文介绍了使用 JavaScript 从 HTML 字符串中提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JS 函数(字符串作为参数传递)获取 HTML 字符串的内部文本.代码如下:

I am trying to get the inner text of HTML string, using a JS function(the string is passed as an argument). Here is the code:

function extractContent(value) {
  var content_holder = "";

  for (var i = 0; i < value.length; i++) {
    if (value.charAt(i) === '>') {
      continue;
      while (value.charAt(i) != '<') {
        content_holder += value.charAt(i);
      }
    }

  }
  console.log(content_holder);
}

extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>");

问题是控制台上没有打印任何内容(*content_holder* 保持为空).我认为问题是由 === 运算符引起的.

The problem is that nothing gets printed on the console(*content_holder* stays empty). I think the problem is caused by the === operator.

推荐答案

创建一个元素,在其中存储 HTML,并获取它的 textContent:

Create an element, store the HTML in it, and get its textContent:

function extractContent(s) {
  var span = document.createElement('span');
  span.innerHTML = s;
  return span.textContent || span.innerText;
};
    
alert(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>"));

这是一个允许您在节点之间有空格的版本,尽管您可能只希望对块级元素使用空格:

Here's a version that allows you to have spaces between nodes, although you'd probably want that for block-level elements only:

function extractContent(s, space) {
  var span= document.createElement('span');
  span.innerHTML= s;
  if(space) {
    var children= span.querySelectorAll('*');
    for(var i = 0 ; i < children.length ; i++) {
      if(children[i].textContent)
        children[i].textContent+= ' ';
      else
        children[i].innerText+= ' ';
    }
  }
  return [span.textContent || span.innerText].toString().replace(/ +/g,' ');
};
    
console.log(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>.  Nice to <em>see</em><strong><em>you!</em></strong>"));

console.log(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>.  Nice to <em>see</em><strong><em>you!</em></strong>",true));

这篇关于使用 JavaScript 从 HTML 字符串中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆