2017-04-03 138 views
0

我有一个字符串,它动态地来自另一个文档,如下所示;使用双引号的字符串正则表达式匹配失败

"<!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变量中的字符串作为它的正上方,在调试时,看我怎么可以让开发者的工具,此正则表达式的工作,我已经改变了开头和结尾双引号的字符串单引号,所以它的工作。然后我将所有双引号改为单引号,并尝试正则表达式函数,但它不起作用。请帮助我正确使用这个正则表达式。

+1

我建议不要使用正则表达式解析HTML [这里](HTTP:// stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)是[why](http://stackoverflow.com/questions/590747/using-regular-expressions-to -parse-html-why-not) – George

+0

感谢您的信息,我会研究我能做些什么。 – ibubi

回答

0

你可以尝试这样的事情:

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

这将启动从<body>直到字符后跟</body>匹配。

此外,由于您收到HTMLString,你会不会有多个body S和因此使用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; 
 
}
<div class="content"></div>

+0

感谢发布,确实我的问题是's'变量来自另一个文档作为字符串,我得到这个字符串,并应用相同的代码,因为你发布,但是匹配是'null'。我不知道为什么,但是如果我在运行时(在调试过程中)将变量的换行字符更改为单引号,则会发生匹配。 – ibubi

+0

@ibubi尝试记录正在获取的原始字符串。如果它以''开头,那么字符串将只是'“<!DOCTYPE html> Rajesh

+0

@ibubi此外,如果问题与您的HTMLString和您的代码工作正常,只是删除评论,我会删除答案,因为它不是必需的。 – Rajesh

相关问题