javascript - Replacing a string unless its in a certain substring of given string -
given long html string, want replace string in html unless it's within <img>
tags of html.
for example, input: text "here"<img src="img_url.jpg" width="100" height="100"></img>
i want replace occurrences of " "
unless quotes within <img>
tags because break urls.
output: text "here"<img src="img_url.jpg" width="100" height="100"></img>
i using input.replace(/"/g, """)
, replaces quotes in string. how replace except substring? not experienced regex, have figured out can detect img tags using /<img[^>]+>/
many in advance help!
assuming attributes valid (i.e. there no <
inside attributes, <img comparison="a<2">
):
var str = 'text "here"<img src="img_url.jpg" width="100" height="100"></img>'; str = str.replace(/(<.*?>)|"/g, function(m, m1) { if (m1) return m1; else return """; }); snippet.log(str);
<!-- provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
but, safer make dom, recurse through text nodes , replacement locally, serialize html again. (edit ...as arun p johny did, i'll upvoting).
also, figured bad idea replace in except in <img>
tags, since things <div class="red">
.
Comments
Post a Comment