Siphon Siphon - 1 month ago 20
Javascript Question

Javascript replace() using html entities

For some reason, the Javascript

replace('search', 'replace')
function works for some HTML entity strings as a search term, but others it does not the way I expect it to. These inconsistencies are very problematic and I can't even work around the issue with the way it works. How can I guarantee these entity search terms will always find the full plain-text word? I need the replace to work the way
‐
does in this example:



$(document).ready(function(){
$('#good').html($('#good').html().replace($('#good').data('text'), 'FOUND'));
$('#okay').html($('#okay').html().replace($('#okay').data('text'), 'FOUND'));
$('#bad').html($('#bad').html().replace($('#bad').data('text'), 'FOUND'));
$('#wrong').html($('#wrong').html().replace($('#wrong').data('text'), 'FOUND'));
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="good" data-text="find">
1: find
</div>
<div id="okay" data-text="&dash;">
2: &dash;
</div>
<div id="bad" data-text="&gt;">
3: &gt;
</div>
<div id="wrong" data-text="&amp;">
4: &amp;
</div>




Answer

Use .text() instead of .html(),as @vlaz suggested. I ran the example using .text(), and it worked fine:

$(document).ready(function(){
  $('#good').text($('#good').text().replace($('#good').data('text'), 'FOUND'));
  $('#okay').text($('#okay').text().replace($('#okay').data('text'), 'FOUND'));
  $('#bad').text($('#bad').text().replace($('#bad').data('text'), 'FOUND'));
  $('#wrong').text($('#wrong').text().replace($('#wrong').data('text'), 'FOUND'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="good" data-text="find">
1: find
</div>
<div id="okay" data-text="&dash;">
2: &dash;
</div>
<div id="bad" data-text="&gt;">
3: &gt;
</div>
<div id="wrong" data-text="&amp;">
4: &amp;
</div>