javascript - 使用正则表达式从解析的 HTML 中获取值

标签 javascript regex

对于一个使网站通信更清晰的项目,我必须使用正则表达式提取消息(为什么?因为消息被注释掉了。使用普通的 document.getElement 我无法访问该消息。但是使用提到的正则表达式下面我可以。)

我正在尝试使用以下表达式获取值:

\s*<td width="61%"class="valorCampoSinTamFijoPeque">(.|\n)*?<\/td>

我如何使用这个表达:

var pulledmessage = /\s*<td width="61%"class="valorCampoSinTamFijoPeque">(.|\n)*?<\/td>/.exec(htmlDoc);

当我 console.log() 时,上面的表达式给我 NULL。我的猜测是我提供正则表达式的 htmlDoc 格式不起作用。我只是不知道如何制作它,这样值(value)就会被拉动。

我用什么来解析 HTML:

var html1 = httpGet(messages);

parser = new DOMParser();

htmlDoc = parser.parseFromString(html1,"text/html");

我想要得到的结果:

<td width="61%"class="valorCampoSinTamFijoPeque"><b>D.</b> De: 
Information, Information. 
Information, Information
Para: Information
CC: Information
Alot of text here ............
</td>

我编辑了上述值以删除个人信息。

html1 包含包含所需信息的完整 HTML 页面。

enter image description here

最佳答案

新的尝试。查看如何注释掉您需要的 td,在解析文档之前从加载的 HTML 文件中删除所有 HTML 注释分隔符。这将导致 td 在文档中呈现,您可以使用 innerHTML 获取消息内容。

const 
  documentString = `
  <!doctype html>
    <html>
    <body>
      <div class="valorCampoSinTamFijoPeque">1</div>
      <div class="valorCampoSinTamFijoPeque">2</div>
      <div class="valorCampoSinTamFijoPeque">3</div>
      <div class="valorCampoSinTamFijoPeque">4</div>
      <div class="valorCampoSinTamFijoPeque">5</div>
      <div class="valorCampoSinTamFijoPeque">6</div>
      <!--<div class="valorCampoSinTamFijoPeque"><b>D.</b> De: Information, Information. Information, Information Para: Information CC: Information Alot of text here ............</div>-->
      <div class="valorCampoSinTamFijoPeque">8</div>
      </body>
    </html>`,
  outputElement = document.getElementById('output');

  debugger;
const
  // Remove all comment delimiters from the input string.
  cleanupDocString = documentString.replace(/(?:<!--|-->)/gm, '');
// Create a parser and construct a document based on the string. It should 
// output 8 divs.
parser = new DOMParser();
htmlDoc = parser.parseFromString(cleanupDocString,"text/html");

const
  // Get the 7th div with the class name from the parsed document.
  element = htmlDoc.getElementsByClassName('valorCampoSinTamFijoPeque')[6];

// Log the element found in the parsed document.
console.log(element);
// Log the content from the element.
console.log(element.innerHTML);
<div id="output"></div>

关于javascript - 使用正则表达式从解析的 HTML 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45979220/

相关文章:

c++ - win7 64 位上的正则表达式构建错误

javascript - JavaScript 中的依赖注入(inject)? (用于数据驱动的可视化)

javascript - 在谷歌地图中使用 ngClass 与 map 缩放事件没有绑定(bind)

javascript - React函数参数是Proxy?

regex - 如何在正则表达式中匹配特定于语言的字符?

javascript - 使用 regExp 将字符串中的多个单词动态匹配到另一个单词

Javascript - 使用全局修饰符删除最后一个不起作用

javascript - 异步函数是否仅用于 IO 阻塞操作?

javascript - 使用 .get 获取 json 数据 jquery

c# - 无法使用正则表达式与 "?"匹配字符串