I have this Sentence
Run the code here: https://stackoverflow.com/questions/58669422/how-to-change-a-part-of-sentence-after-specific-string-in-javascript/58669900#58669900
" Hi ~r~ I'm the ~b~ BOSS "
I want to change string after
"~r~"
by putting it in a span with red color, and string after " ~b~ "
by putting it in a span with black color. This example has just 2 colors but I may want to have many more colors with other codes I want the output string to look something like the following:"Hi" + "<span style='color: red;'>i'm the</span>" + "<span style='color: black;'>BOSS</span>"
Answer 1
function addColors(ele) {
let str = ele;
let hasSpan = false;
let ansStr = "";
for(let i=0; i<str.length; i++) {
if(str[i] === '~') {
i++;
switch(str[i]) {
case 'r':
if(hasSpan) {
ansStr = str.slice(0, i-1) + "<span><span style='color: red;'>" + str.slice(i+2);
} else {
ansStr = str.slice(0, i-1) + "<span style='color: red;'>" + str.slice(i+2);
hasSpan = true;
}
str = ansStr;
i = i+2;
break;
case 'b':
if(hasSpan) {
ansStr = str.slice(0, i-1) + "<span><span style='color: black;'>" + str.slice(i+2);
} else {
ansStr = str.slice(0, i-1) + "<span style='color: black;'>" + str.slice(i+2);
hasSpan = true;
}
str = ansStr;
i = i+2;
break;
default:
console.log(i, str[i+1], "DEFAULT")
}
}
}
if(hasSpan) {
str = str + "</span>"
}
document.querySelector('h1').innerHTML = str;
}
<h1>WATCH THIS!</h1>
<input type="text" name="jhtml" value="Hi ~r~ I'm the ~b~ BOSS">
<button onclick="addColors(document.getElementsByName('jhtml')[0].value)">Add Colors</button>
Answer 2: Regex
let text = " Hi ~r~ I'm the ~b~ BOSS "
let colors = { r: 'red', b: 'blue' }
document.h1.innerHTML = text.replace(/~([a-z])~(.*?)(?=~|$)/g, (match, p1, p2) => {
return `<span style="color:${colors[p1]}">${p2}</span>`
})
Comments
Post a Comment