css中字符串的模式匹配

时间:2017-05-18 13:49:39

标签: javascript html css css-selectors

我们在css中有什么内容可以将样式应用于一组匹配的关键字吗?

例如,我有一个单词列表{“历史”,“领导者”,“情绪”,“时间”...}

我想将css样式应用于以下段落中与上面列表匹配的所有关键字。


“纵观人类历史,或者最伟大的领导者和思想家利用词汇的力量来改变我们的情感,让我们加入他们的导致并塑造命运的过程。词语不仅可以创造情感,还可以创造行动。从我们的行动中流出我们生活的结果。“Tony Robbins

1 个答案:

答案 0 :(得分:0)

  

感谢大家的投入。我会去javascript编辑html代码   在应用css之前。

这是一种方法,展示了如何在阵列中循环:

['history', 'leaders', 'emotions', 'time']

并加粗文字中的每个单词。

var wordsToHighlight = ['history', 'leaders', 'emotions', 'time'];

var paragraph2 = document.getElementsByTagName('p')[1];
var paragraph2Text = paragraph2.innerHTML;
var paragraph2RichText = paragraph2Text;

for (var i = 0; i < wordsToHighlight.length; i++) {
    var regex = new RegExp('('+ wordsToHighlight[i] + ')', 'gi');
    paragraph2RichText = paragraph2RichText.replace(regex, '<strong>$1</strong>');
}

paragraph2.innerHTML = paragraph2RichText;
<p>“Throughout human history, or greatest leaders and thinkers have used the power of words to transform our emotions, to enlist us in their causes, and to shape the course of destiny. Words can not only create emotions, they create actions. And from our actions flow the results of our lives.” Tony Robbins</p>
<p>“Throughout human history, or greatest leaders and thinkers have used the power of words to transform our emotions, to enlist us in their causes, and to shape the course of destiny. Words can not only create emotions, they create actions. And from our actions flow the results of our lives.” Tony Robbins</p>

相关问题