想法:
我想突出显示用大括号输入的字符串中的单词(例如“Lorem {Ipsum} Sit Dolor”)。如果它们匹配,则应应用 font-weight: bold。
到目前为止的方法:
var final = [];
var regExp = /([^{]*?)(?=\})/;
var string = document.getElementById("myParagraph").innerHTML;
wordArray = string.split(/\s+/);
for (var i = 0; i < wordArray.length; i++) {
if (regExp.exec(wordArray[i])) {
final.push(wordArray[i]);
}
}
console.log(final);
<body>
<p id="myParagraph">This is a test string with a {bold} text. Lets {see} if this works</p>
</body>
现在我明白了我需要用 CSS 突出显示的话,并且会用 jQuery.css() 做一个 jQuery.each,但我现在不确定如何应用样式并自动“刷新”DOM。
最佳答案
您可以使用 String.prototype.replace 大大简化您的代码并直接写入元素的 innerHTML。
Regex 也有点不同,因为我假设您不想在输出中保留大括号,因此它们不会保留在捕获组中。
就样式而言,您可以将元素包装在具有特定类的范围内,但我只使用了原生 strong
标记,因为它在语义上是正确的并且具有您所追求的样式默认。
function bolderize(el) {
el.innerHTML = el.innerHTML.replace(/{([^}]+)}/gm, '<strong>$1</strong>')
}
bolderize(document.getElementById('myParagraph'))
<body>
<p id="myParagraph">This is a test string with a {bold} text. Lets {see} if this works lol</p>
</body>
关于javascript - 如果正则表达式模式匹配,则字符串中的粗体字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39854163/