Reputation: 21
I'm trying to use javascript to replace characters in a paragraph with styled characters. If I replace one character with one style it works fine, but when I try to replace 3 different characters with 3 different styles the paragraph is printed 3 times, each with only 1 style change. I want the 3 styles to take effect in 1 paragraph. Below is the code I am using. Thank you.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction (){
var pText=document.getElementById("alteredText").innerHTML;
var eSpan=pText.replace(/e/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");
var tSpan=pText.replace(/t/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");
var sSpan=pText.replace(/s/g,"<span style='color:green;'>s</span>");
var n = eSpan.concat(tSpan,sSpan);
document.getElementById("alteredText").innerHTML=n;
}
</script>
</head>
<body onLoad="myFunction()">
<p id="alteredText">
The quick brown fox jumped over the lazy sleeping dog.
The slow shiny robot chased the quick brown fox.
The lazy sleeping dog awoke and barked at the slow shiny robot.
</p>
</body>
</html>
Upvotes: 2
Views: 1043
Reputation: 2153
one quick&dirty solution:
function myFunction (){
var pText=document.getElementById("alteredText").innerHTML;
var eSpan=pText.replace(/e/g,"<SPAN STYLE='POSITION:RELATIVE;COLOR:RED;TOP:.05EM;'>e</SPAN>"); // CAPS are needed so no match is found in the next replace
var tSpan=eSpan.replace(/t/g,"<SPAN STYLE='POSITION:RELATIVE;COLOR:BLUE;TOP:-.05EM;'>t</SPAN>");
var sSpan=tSpan.replace(/s/g,"<SPAN STYLE='COLOR:GREEN;'>s</SPAN>");
// var n = eSpan.concat(tSpan,sSpan); //<-- this creates the three copies of the paragraph. you don't need this.
document.getElementById("alteredText").innerHTML=sSpan;
}
see http://jsfiddle.net/DUN4C/
Upvotes: 0
Reputation: 1565
var pText=document.getElementById("alteredText").innerHTML;
var t = pText.replace(/e/g,"@e@");
t = t.replace(/t/g,"@t@");
t = t.replace(/s/g,"@s@");
t = t.replace(/@e@/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");
t = t.replace(/@t@/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");
t = t.replace(/@s@/g,"<span style='color:green;'>s</span>");
document.getElementById("alteredText").innerHTML=t;
Upvotes: 2
Reputation: 142
Try this:
var first = pText.replace(/e/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");
var second = first.replace(/t/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");
var final = second.replace(/s/g,"<span style='color:green;'>s</span>");
document.getElementById("alteredText").innerHTML=final;
See what I've done? You were creating three string, each one with one replacement. Here I'm doing the second replacement in the string that already contain the first one. After the last replacement, I put it in the element.
Upvotes: -1