3

I'm trying to replace multiple words in same div.
Obviously this won't work, here my code.

$("#Number").each(function() {
    var text = $(this).text();
    $(this).text(text.replace("Monster", "Witch")); 
});
$("#Number").each(function() {
    var text = $(this).text();
    $(this).text(text.replace("Girl", "Boy")); 
});

Thank you.

rageandqq
  • 2,221
  • 18
  • 24
giangi90
  • 31
  • 1
  • 2
  • 6
  • possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – Artjom B. Feb 19 '15 at 21:04

2 Answers2

5

Replace can't accept multiple parameters but you can chain it, eg:

$("#Number").each(function() {
    $(this).html($(this).html().replace('find1', 'replace1').replace('find2', 'replace2'));
});
Camway
  • 1,010
  • 14
  • 23
3

You can simply use regex to replace all occurrences in a string.

$(".Number").each(function() {
    $(this).text($(this).text().replace(/Monster/g, "Witch")); 
});
$(".Number").each(function() {
    $(this).text($(this).text().replace(/Girl/g, "Boy")); 
});

See a working JSFiddle here.

Note: Keep in mind, you can't have two elements with the same IDs (denoted by '#'). So, I changed the attribute and selector to class.
If you only want to change the value on one element, you can move the logic from the second block to the body of the first:

$("#Number").each(function() {
    $(this).text($(this).text().replace(/Monster/g, "Witch")); 
    $(this).text($(this).text().replace(/Girl/g, "Boy")); 
});
rageandqq
  • 2,221
  • 18
  • 24
  • 2
    "you can't have two elements with the same IDs" there isn't any reason you can't, although it is against convention, rails pages do this all the time. If you need to grab all of them just change your selector to: $('[id=Number]'). The '#' in the query just tells the javascript to return the first record only. – Camway Feb 19 '15 at 20:58
  • Fair enough, I guess I mean you *shouldn't* have two elements with the same ID. – rageandqq Feb 19 '15 at 21:08