我目前正在尝试使用正则表达式来改变单词" Kanye"以红色显示。
然而,它没有出现:
<div id="kanye">
<center>
<p>I miss the old Kanye,</p>
<p> straight from the Go Kanye
<p>Chop up the soul Kanye, set on his goals Kanye</p>
<p>I hate the new Kanye, the bad mood Kanye</p>
<p>The always rude Kanye, spaz in the news Kanye</p>
<p>I miss the sweet Kanye, chop up the beats Kanye</p>
<p>I gotta say, at that time I'd like to meet Kanye</p>
<p>See, I invented Kanye, it wasn't any Kanyes</p>
<p>And now I look and look around and there's so many Kanyes</p>
<p>I even had the pink polo, I thought I was Kanye</p>
<p>What if Kanye made a song about Kanye</p>
<p>Called "I Miss The Old Kanye"? Man, that'd be so Kanye</p>
<p>That's all it was Kanye, we still love Kanye</p>
<p>And I love you like Kanye loves Kanye</p>
</center>
</div>
脚本如下:
<script>
var text = document.getElementById("kanye");
var str = kanye.innerHTML;
reg = /\[Kanyes?|yeezy/ig
var toStr = String(reg);
var color = (toStr.replace('\/g', '|')).substring(1);
var colors = color.split("|");
if (colors.indexOf("kanye") > -1) {
str = str.replace(/\[Kk]anyes?/g, '<span style="color:red;">red</span>');
}
document.getElementById("updated").innerHTML = str;
</script>
我没有正确使用跨度?再次感谢!
答案 0 :(得分:0)
这适用于您的情况,您也可以查看不同的 Kanyes 。
var text = document.getElementById("kanye");
var str = kanye.innerHTML;
if (str.toLowerCase().indexOf("kanye") > -1) {
str = str.replace(/kanyes/ig, '<span style="color:red;">Kanyes</span>');
str = str.replace(/kanye/ig, '<span style="color:red;">Kanye</span>');
}
document.getElementById("kanye").innerHTML = str;