简体   繁体   中英

JavaScript conditional font color change of part of text

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?

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>

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(/[AZ&]/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>

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("[AZ]{2,}","g"), res = str.replace(rgx, s => `<span style="color:red;">${s}</span>`); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM