改变给定句子关键词的颜色

我想改变给定句子关键词的颜色。到目前为止我有这个:


const engSample = document.querySelector(".eng-sample");


engSample.innerHTML = getColoredEngSample("I have been walking");


function getColoredEngSample(text) {


        let result;

        const keywords = ["have", "has", "been", "ing"];

        keywords.forEach(key => {

            result = text.replace(key, `<span class='bold-sample'>${key}</span>`);

        });

    return result;

}

.bold-sample { color: #ff3c00; }

<p class="eng-sample"></p>


如您所见,只有ing颜色发生变化,而其余关键字则没有。


我该如何解决这个问题或使用正则表达式获得相同的结果?


偶然的你
浏览 145回答 2
2回答

米脂

您在每次迭代中都将替换result为 original text。因此,您应该将代码更改为:function getColoredEngSample(text) {&nbsp; &nbsp; let result = text;&nbsp; &nbsp; const keywords = ["have", "has", "been", "ing"];&nbsp; &nbsp; keywords.forEach(key => {&nbsp; &nbsp; &nbsp; &nbsp; result = result.replace(key, `<span class='bold-sample'>${key}</span>`);&nbsp; &nbsp; });&nbsp; &nbsp; return result;}

HUX布斯

问题是您使用的变量text不会随时间变化。每次循环开始一轮时,它都会使用来自参数的相同文本text。在循环的下一次运行中,文本更改被写入结果但不再使用。所以 result 将只包含最后一次循环的结果。const engSample = document.querySelector(".eng-sample");engSample.innerHTML = getColoredEngSample("I have been walking");function getColoredEngSample(text) {&nbsp; &nbsp; &nbsp; &nbsp; let result = text;&nbsp; &nbsp; &nbsp; &nbsp; const keywords = ["have", "has", "been", "ing"];&nbsp; &nbsp; &nbsp; &nbsp; keywords.forEach(key => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = result.replace(key, `<span class='bold-sample'>${key}</span>`);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; return result;}.bold-sample { color: #ff3c00; }<p class="eng-sample"></p>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript