M4N1F3S7O
M4N1F3S7O

Reputation: 15

How to change colour of specific characters [jQuery/RegEx]

Looking to change the colour of specific characters. Having problems achieving this the return values are being overwritten with the new values. Tried placing this in a loop to parse through the characters but then got lost in the flow.

  1. HTML contains the raw text.
  2. The colours are defined in the CSS.
  3. RegEx are containing the specific characters for replacement (e.g. Uppercase A and/or lower case a) in the first run.
  4. jQuery contains the function to change the specific characters.

Here is the example:

$(document).ready(function() {
  $("#container p").html(function(_, html) {
    return html.replace(/([Aa])/g, '<span class="red">$1</span>');
  });
  $("#container p").html(function(_, html) {
    return html.replace(/([Ee])/g, '<span class="blue">$1</span>');
  });
  $("#container p").html(function(_, html) {
    return html.replace(/([Rr])/g, '<span class="green">$1</span>');
  });
  $("#container p").html(function(_, html) {
    return html.replace(/([Oo])/g, '<span class="yellow">$1</span>');
  });
});
.red {
  color: red
}

.blue {
  color: blue
}

.green {
  color: green
}

.yellow {
  color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <p>aero aero aero</p>
</div>

jQuery returns scrambled HTML.

Upvotes: 0

Views: 132

Answers (1)

Seegy
Seegy

Reputation: 392

To prevent overwriting values that have already been written, I created a new string to store the values then finally replace the old string.

$(document).ready(function() {
  var newString = '';
  for(var i = 0; i < $("#container p").html().length; i++) {
  	switch($("#container p").html()[i].toLowerCase()) {
    	case 'a':
      	newString += '<span class="red">' + $("#container p").html()[i] + '</span>';
      	break;
      case 'e':
      	newString += '<span class="blue">' + $("#container p").html()[i] + '</span>';
        break;
      case 'r':
      	newString += '<span class="green">' + $("#container p").html()[i] + '</span>';
        break;
      case 'o':
      	newString += '<span class="yellow">' + $("#container p").html()[i] + '</span>';
        break;
      default:
      	newString += $("#container p").html()[i];
    }
  }
  $("#container p").html(newString);
});
.red {
  color: red;
}

.blue {
  color: blue;
}

.green {
  color: green;
}

.yellow {
  color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <p>aero aero aero</p>
</div>

Upvotes: 1

Related Questions