0

Simply, How can I replace exact text with HTML using jQuery?

The original text is View All Customer Reviews

I want it to be replaced with <span class="redbutton">View All Reviews &#187;</span>

Thanks.

6
  • Is this text in some html element? Commented Jan 11, 2012 at 6:59
  • Yes, an anchor, but the anchor is not classified nor identified Commented Jan 11, 2012 at 7:00
  • you shouldn't need jQuery for this. Javascript has a built in regex match/replace functionality. Commented Jan 11, 2012 at 7:08
  • 1
    @Brombomb Would you happen to have a solution? Commented Jan 11, 2012 at 7:08
  • The solution by @Wally-Qiao below is perfectly acceptable Commented Jan 11, 2012 at 7:10

2 Answers 2

2
<div id="_div">xxx|||View All Customer Reviews|||xxx</div>
<script>
$(function() {
var html = $('#_div').html() + '';
html = html.replace(/View All Customer Reviews/g, '<span class="redbutton">View All Reviews &#187;</span>');
$('#_div').html(html);
});
</script>

// ===================----================== ///

<a>xxx|||View All Customer Reviews|||xxx</a>
<a>yyy|||View All Customer Reviews|||yyy</a>
<a>zzz|||View All Customer Reviews|||zzz</a>
<script>
$(function() {
    $('a').each(function(i) {
        var html = $(this).html() + '';
        html = html.replace(/View All Customer Reviews/g, '<span class="redbutton">View All Reviews &#187;</span>');
        $(this).html(html);
    });
});
</script>
Sign up to request clarification or add additional context in comments.

11 Comments

My content isn't wrapped in a div
If you provided what your content is wrapped in we'd be able to help you more specifically. This solution show how to use jQuery to grab the contents of any html element by id and then replace the text.
@Brombomb I know I understand the content is wrapped in an unclassified anchor
use $('a') to grab all anchors. You should be able to narrow this down somewhat with some parent div/class selector.
else if using \r\n and tabs, html.replace(/View(\s*[\r\n|\t]\s*)All Customer Reviews/g, ...) @user1090389
|
0

Try this :

http://benalman.com/projects/jquery-replacetext-plugin/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.