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 " &quot; unless quotes within <img> tags because break urls.

output: text &quot;here&quot;<img src="img_url.jpg" width="100" height="100"></img>

i using input.replace(/"/g, "&quot;"), 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 "&quot;";  });  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=&quot;red&quot;>.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -