【问题标题】:Regex match fails on string with double quotes正则表达式匹配在带有双引号的字符串上失败
【发布时间】:2017-04-03 13:09:15
【问题描述】:

我有一个动态来自另一个文档的字符串,如下所示;

"<!DOCTYPE html>
<html dir="ltr"><head><title>Preview</title></head>
<body>
<p>test</p>
<p><img alt="" height="299" src="http://172.0.0.1/Administration/YDImages/cap.JPG" width="696"></p>
</body>
</html>"

我使用这个字符串如下;

var html = stringAbove; 
var reg = html.match(/<body[^>]*>(.*)<\/body>/);
var newDocument = "<p>My new Texts and styles</p>"; //replace inside body with my new code
var newer = html.replace(reg[1],newDocument);
doc.write(newer);

我发现html.match 返回null 如果上面的 html 变量中的字符串,在调试以查看如何使此正则表达式在开发人员工具上工作时,我已经更改了开始和结束双引号将字符串转换为单引号,所以它起作用了。然后我将所有双引号更改为单引号并尝试正则表达式函数,但它不起作用。请帮我让这个正则表达式正常工作。

【问题讨论】:

  • 我建议不要使用正则来解析html Here is why
  • 感谢您的信息,我会研究我能做什么。

标签: javascript regex


【解决方案1】:

你可以试试这样的:

/<body>(.*?)(?=<\/body>)/

这将从&lt;body&gt; 开始匹配,直到字符后面跟着&lt;/body&gt;

此外,由于您正在接收 HTMLString,因此您不会有多个 bodys,因此使用 match[0]

var s = '<!DOCTYPE html><html dir="ltr"><head><title>Preview</title></head><body><p>test</p><p><img alt="" height="299" src="http://172.0.0.1/Administration/YDImages/cap.JPG" width="696"></p></body></html>';

var regex = /<body>(.*?)(?=<\/body>)/;

var match = s.match(regex)
console.log(match)
var html = match[0].replace("<body>", "")

document.querySelector('.content').innerHTML = html
img{
  border: 1px solid gray;
}
&lt;div class="content"&gt;&lt;/div&gt;

【讨论】:

  • 感谢您的帖子,确实我的问题是s 变量来自另一个文档作为字符串,我得到这个字符串并应用与您发布的相同的代码,但匹配是null。我不知道为什么,但是如果我在运行时(调试时)将变量的包装 qoutes 更改为单引号,就会发生匹配。
  • @ibubi 尝试记录你得到的原始字符串。如果它以" 开头,那么字符串将只有"&lt;!DOCTYPE html&gt; &lt;html dir=",因此匹配将为空
  • @ibubi 另外,如果问题出在您的 HTMLString 并且您的代码工作正常,只需发表评论,我将删除不需要的答案。
  • 正是它.. 字符串以" 开头,代码工作正常。如何获得完整的 html 字符串而不会损坏?
  • @ibubi 我们需要看看你现在是如何获取 HTML 字符串的。你可以尝试html.replace(/"/g, "\"") 来逃避它,但如果这段代码可用,我们可以提供更好的帮助。也可以查看encodeURI
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 2016-07-29
  • 2010-09-13
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多