I have a string of HTML, in this example it looks like
<img src="somepic.jpg" someAtrib="1" >
I am trying to workout a peice of regex that will match the 'img' node and apply a slash to the end of the node so it looks like.
<img src="somepic.jpg" someAtrib="1" />
Essentially the end goal here is to ensure that the node is closed, open nodes are valid in HTML but not XML obviously. Are there any regex buff's out there able to help?
This will do a pretty good job:
Addendum: In the (unlikely) event that your code contains tag attributes containing angle brackets (which is not vaild XML/XHTML BTW), then this one will do a little better job:
Why would u wanna fix in browser DOM a HTML document that's XHTML invalid?
It was already served and parsed and you already have DOM available. Any parsing error that an invalid/bad formed document would cause, already happened and it won't be a regex on DOM that will fix it.
Also, remember that almost all documents are parsed as HTML tag-soup. If you can't fix the document on server-side, just ignore its validity/wellformeness on client-side.
Don't use a Regular expression, but dedicated parsers. In JavaScript, create a document using the
DOMParser
, then serialize it using theXMLSerializer
:In addition to Rob W's answer, you can extract the body content using RegEx:
Note:
parseFromString(htmlString, 'text/html');
would throw error in IE9 because text/html mimeType is not supported in IE9. Works with IE10 and IE11 though.You can create a xhtml document and import/adopt html elements. Html strings can be parsed by HTMLElement.innerHTML property, of cause. The key point is using Document.importNode() or Document.adoptNode() method to convert html nodes to xhtml nodes:
The output should be:
Rob W's answer does not work in chrome (at least 29 and below) because DOMParser does not support 'text/html' type and XMLSerializer generates html syntax(NOT xhtml) for html document in chrome.