0

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>

8
  • 4
    Have you tried .text() instead of .html()? Commented Nov 7, 2016 at 17:39
  • What are the inconsistencies you are having? Commented Nov 7, 2016 at 17:39
  • 1
    Tried you're example with @vlaz suggestion of replacing .html() with .text(). Works perfectly... Commented Nov 7, 2016 at 17:41
  • @MB run the code snippet. OP basically wants to replace the HTML content with...the HTML content replaced with the string FOUND Commented Nov 7, 2016 at 17:41
  • Sure enough, .text() fixes the problem! Commented Nov 7, 2016 at 17:57

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.