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 »</span>
Thanks.
asked Jan 11, 2012 at 6:48
henryaaron
6,22221 gold badges64 silver badges83 bronze badges
-
Is this text in some html element?Oleksandr Fentsyk– Oleksandr Fentsyk2012年01月11日 06:59:51 +00:00Commented Jan 11, 2012 at 6:59
-
Yes, an anchor, but the anchor is not classified nor identifiedhenryaaron– henryaaron2012年01月11日 07:00:20 +00:00Commented Jan 11, 2012 at 7:00
-
you shouldn't need jQuery for this. Javascript has a built in regex match/replace functionality.Brombomb– Brombomb2012年01月11日 07:08:00 +00:00Commented Jan 11, 2012 at 7:08
-
1@Brombomb Would you happen to have a solution?henryaaron– henryaaron2012年01月11日 07:08:55 +00:00Commented Jan 11, 2012 at 7:08
-
The solution by @Wally-Qiao below is perfectly acceptableBrombomb– Brombomb2012年01月11日 07:10:10 +00:00Commented Jan 11, 2012 at 7:10
2 Answers 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 »</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 »</span>');
$(this).html(html);
});
});
</script>
Sign up to request clarification or add additional context in comments.
11 Comments
henryaaron
My content isn't wrapped in a div
Brombomb
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.henryaaron
@Brombomb I know I understand the content is wrapped in an unclassified anchor
Brombomb
use
$('a') to grab all anchors. You should be able to narrow this down somewhat with some parent div/class selector.Wally Qiao
else if using \r\n and tabs, html.replace(/View(\s*[\r\n|\t]\s*)All Customer Reviews/g, ...) @user1090389
|
answered Jan 11, 2012 at 6:58
Mandeep Pasbola
2,6392 gold badges27 silver badges50 bronze badges
Comments
lang-js