如何在javascript中使某个单词加粗?



所以我有这个数组的问题写在js。我可以这样访问我的html:

const questionIndex = availableQuestion[arrayReady[currentPage-1]];
currentQuestion = questionIndex;
questionText.innerHTML = currentQuestion.q;

我怎样才能使一个词像= "not","except"从currentQuestion。问大胆?

您需要一个要加粗的单词列表,遍历它们,在currentQuestion.q中找到它们,然后加粗它们。

const currentQuestion = {}
currentQuestion.q = "This is not a not really except good question."
console.log(currentQuestion.q)
const boldWords = ["not", "except"]
boldWords.forEach(word => {
currentQuestion.q = currentQuestion.q.replace(new RegExp("(" + word + ")", "g"), makeBold("$1"))
})
console.log(currentQuestion.q)
function makeBold(str) {
// your bold implementation
return str.bold()
}

我查看了所有的答案,但我已经开发了一个更浏览器兼容的代码相比,已经存在的答案。请看下面。

<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a string in bold.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
const str = "Hello Javesh, How are you doing today?"; //your question
const result = str.split(" ");
const keywords = ["Hello", "How"]; // your keywords
for(var i = 0; i<result.length; i++){
if(keywords.includes(result[i])){       
document.querySelector("#demo").innerHTML += "<b>"+result[i]+"</b>"+" ";
}else{
document.querySelector("#demo").innerHTML +=result[i]+" ";
}
}  
}
</script>
</body>
</html>

bold()功能被低估,因为它的功能可能因浏览器而异。

bold()函数的MDN参考:-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/bold

您可以使用bold()函数并将其与循环和条件结合使用

您可以使用bold() <-(这是一个函数)并与循环/条件一起使用

最新更新