JavaScript 正则表达式替换宽度属性匹配 [英] JavaScript Regex Replace Width Attribute Matching

查看:78
本文介绍了JavaScript 正则表达式替换宽度属性匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RegEx 从文本区域匹配一组更窄的 TinyMCE HTML.宽度太大,会产生径流,所以我用 JavaScript 编写测试代码.

I am using RegEx to match a narrower set of TinyMCE HTML from a textarea. Widths are too big, creating run-offs so I am making test code in JavaScript.

我的问题是为什么 $3 不仅匹配1000px"而且匹配表格标签之后的文档的其余部分?

My question is why does $3 not only match "1000px" but also matches the rest of the document after the table tag?

<script language="javascript">
  // change table width
  function adjustTable(elem0,elem1) {
    // debugging, place results in div
    elem1.innerHTML = elem0.innerHTML.replace(/^(.*)(\u003Ctable.*?\s*?\w*?width\u003D[\u0022\u0027])(\d+px)([\u0022\u0027].*?\u003E)(.*)$/img,"$3");
  }
</script>

<button type="button" onclick="adjustTable(document.getElementById('myTable'),document.getElementById('myResult'))">RegEx</button>

<div id="myTable">
  <table width="1000px">
    <thead>
      <tr><th colspan="3">Table Header</th></tr>
    </thead>
    <tbody>
      <tr><td>alpha</td><td>beta</td><td>gamma</td></tr>
    </tbody>
  </table>
</div>
<textarea id="myResult">
</textarea>

<textarea id="myResult"></textarea>

Yes, I do understand RegEx and HTML are streams that should not be crossed, because HTML is complex, etc. I am attempting to make the subset of HTML printable.

是的,我确实理解 RegEx 和 HTML 是不应该交叉的流,因为 HTML 很复杂,等等.我正在尝试使 HTML 的子集可打印.

I do not see how it matches in multiple ways.

我看不出它是如何以多种方式匹配的.

Below is the result for $3.

以下是 3 美元的结果.

1000px <thead> <tr><th colspan="3">Table Header</th></tr> </thead> <tbody> <tr><td>alpha</td><td>beta</td><td>gamma</td></tr> </tbody> </table>

It matches the 1000px, but then there's the extraneous stuff after the table tag, which is odd, because I thought I was forcing a match in the table tag. Thoughts?

它与 1000px 匹配,但是在 table 标记之后有无关的东西,这很奇怪,因为我以为我在 table 标记中强制匹配.想法?

解决方案

推荐答案

让我们通过记录正则表达式的整个结果来调试它:

function adjustTable(elem0,elem1) { // debugging, place results in div console.log ( (/^(.*)(\u003Ctable.*?\s*?\w*?width\u003D[\u0022\u0027])(\d+px)([\u0022\u0027].*?\u003E)(.*)$/img).exec(elem0.innerHTML) ); }

The output is: 

输出为:

所以如果你想得到结果1000px",那么使用这个代码:

So if you want to get the result "1000px", then use this code:

(/^(.*)(\u003Ctable.*?\s*?\w*?width\u003D[\u0022\u0027])(\d+px)([\u0022\u0027].*?\u003E)(.*)$/img).exec(elem0.innerHTML)[3]

这篇关于JavaScript 正则表达式替换宽度属性匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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