2

I'm currently working on a website with Game maker tutorials. Sometimes I have to put a few lines of code onto the website. To make it look more like Game maker itself, I would like to change the color of specific characters and words in the text.

Right now I'm trying to change the color of all the X and Y's. This is what I have right now:

$(document).ready(function(){
    $(".code").children().each(function() {
        $(this).html($(this).html().replace(/\x\b/g, "<font color=red>x</font>"));
        $(this).html($(this).html().replace(/\X\b/g, "<font color=red>X</font>"));
        $(this).html($(this).html().replace(/\y\b/g, "<font color=red>y</font>"));
        $(this).html($(this).html().replace(/\Y\b/g, "<font color=red>Y</font>"));
    });
})

While it does color the characters, it also colours characters in a word, which is not what I want. What do I add or change so it will only color X and Y's that are not in a word?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Lolslayer
  • 63
  • 8
  • 4
    Note that the method you're using will potentially break the HTML in the page if an `X` or `Y` is in an attribute of an element. Instead it would be better to loop over the `textNodes` within the whole document and update them if they contain the text you're looking for. See [this answer](http://stackoverflow.com/a/16662482/519413) for how to do that. – Rory McCrossan Jan 13 '16 at 13:57
  • Also wrap in a span with a class instead of using deprecated font – mplungjan Jan 13 '16 at 14:01
  • Thank you for your respond, but before I'll read the code in detail I want to know if it will actually replace texts, because as far as I've read at the moment it seems like it will only wrap words in a span – Lolslayer Jan 13 '16 at 14:12
  • I hope you ll check the answer =) – Kamuran Sönecek Jan 14 '16 at 06:34

1 Answers1

0

I think these codes can solve your problem. Just started with \b for regex

$(document).ready(function(){
    $(".code").children().each(function() {
        $(this).html($(this).html().replace(/\b\x\b/g, "<font color=red>x</font>"));
        $(this).html($(this).html().replace(/\b\X\b/g, "<font color=red>X</font>"));
        $(this).html($(this).html().replace(/\b\y\b/g, "<font color=red>y</font>"));
        $(this).html($(this).html().replace(/\b\Y\b/g, "<font color=red>Y</font>"));
    });
});

http://jsfiddle.net/fno9d6wz/

Kamuran Sönecek
  • 3,293
  • 2
  • 30
  • 57