Home > OS >  JavaScript conditional font color change of part of text
JavaScript conditional font color change of part of text

Time:12-12

I tried to change the font color of my String in my vue application based on a condition. However, the solutions I found so far changed the color for the whole text. I only want specific parts to be changed. For example:

const exampleString= 'Yesterday I was ACTIVITY with FRIEND who I first met in PLACE'

The words in capital letters should be in color red but the rest in black. So a condition like "if three subsequent chars are capital letters than color red until empty space". Is there a way to implement this ?

CodePudding user response:

Yes you can do it. You can simply loop over your content and add a condition that all the letters in a word should have the appropriate ascii value for capital letters, and if it passes this check, you can specify the color in a span tag. Here's a pure JavaScript example:

var para = document.getElementById("para").innerHTML;
var resultPara = "";
var words = para.split(" ");

for (var word of words) {
  var capitalLetterCount = 0;
  for (var letter of word) {
    if (letter.charCodeAt(0) >= 65 && letter.charCodeAt(0) <= 90)
      capitalLetterCount  ;
    else
      break;
  }
  if (capitalLetterCount != 0 && capitalLetterCount === word.length)
    resultPara  = ' <span style="color: red">'   word   '</span>';
  else
    resultPara  = ' '   word;
}
document.getElementById("para").innerHTML = resultPara;
<div id="para">Yesterday I was ACTIVITY with FRIEND who I first met in PLACE</div>

CodePudding user response:

If you ask how to do that with Vue, you can try with v-html:

new Vue({
  el: "#demo",
  data() {
    return {
      text: "Yesterday I was ACTIVITY with FRIEND who I first met in PLACE"
    }
  },
  computed: {
    setText() {
      return this.text.replace(/[A-Z&]/g, m => `<span style="color: red;">${m}</span>`)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-html="setText"></div>
</div>

CodePudding user response:

I don't use Vue but you may simply insert necessary <span>s with inline styling like;

var str = 'Yesterday I was ACTIVITY with FRIEND who I first met in PLACE',
    rgx = new RegExp("[A-Z]{2,}","g"),
    res = str.replace(rgx, s => `<span style="color:red;">${s}</span>`);

console.log(res);

  • Related