简体   繁体   English

正则表达式匹配在带双引号的字符串上失败

[英]Regex match fails on string with double quotes

I have a string that dynamically comes from another document as follows; 我有一个动态地来自另一个文档的字符串,如下所示;

"<!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>"

I use this string as follows; 我使用这个字符串如下:

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);

I've discovered that html.match returns null if the string inside html variable as it is above, while debugging to see how could I make this regex work on developer tools, I've changed starting and ending double quotes of the string to single quotes, so it worked. 我发现如果html变量中的字符串如上所示,则html.match返回null ,在调试以查看如何使此正则表达式在开发人员工具上工作时,我已将字符串的双引号和双引号改为单引号引号,因此有效。 Then I changed all double quotes to single quotes and try regex function but it doesn't work. 然后,我将所有双引号更改为单引号,并尝试使用regex函数,但是它不起作用。 Please, help me to get this regex work properly. 请帮我使此正则表达式正常工作。

You can try something like this: 您可以尝试如下操作:

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

This will start matching from <body> till the character followed by </body> . 这将从<body>匹配直到字符跟</body>开始匹配。

Also since you are receiving HTMLString, you will not have multiple body s and hence using match[0] 另外,由于您正在接收HTMLString,因此不会有多个body ,因此使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM