假设我有一根绳子:
这件事发生在这简直太离谱了!一场大龙卷风可能会向你袭来。但我不确定!
我如何通过Javascript或Jquery使其部分大胆,从而使其变成如下:
这件事发生在这简直太离谱了!一场大的龙卷风可能会向你袭来。,但我不确定!
在“龙卷风”之前添加一个<b>,在龙卷风之后的第一个周期之后添加一个</b>。
因此,规则是:“查找”龙卷风“一词,在”龙卷风“之前添加一个”<b>“,并在”龙卷风“一词之后的第一个句号之后添加”</b>“
希望能在这方面提供任何帮助!
发布于 2019-03-23 18:15:28
下面的示例使用正则表达式和基本DOM操作来实现您所描述的目标。
function highlightFromWordToPeriod(words) {
let el = document.querySelector('.my-text');
el.innerHTML = el.innerHTML.replace(new RegExp(`((${words.join('|')})[^.]*.)`, 'g'), "<b>$&</b>");
}<div class="my-text">This has happened at it's outrageous! A big tornado might be coming towards you. But I'm not certain! Watch out for hurricane as well.
</div>
<p>
<button onclick="highlightFromWordToPeriod(['tornado', 'hurricane'])">Replace</button>
发布于 2019-03-23 18:30:43
首先,使用正则表达式选择要粗体的句子的部分。然后简单地使用字符串替换方法。
var str = "This has happened at it's outrageous! A big tornado might be coming towards you. But I'm not certain!";
var matchRes = str.match(/tornado[\w\s\W]*\./);
str = str.replace(matchRes[0], "<b>"+matchRes[0]+"</b>");
console.log(str);
// This has happened at it's outrageous! A big <b>tornado might be coming towards you.</b> But I'm not certain!https://stackoverflow.com/questions/55316641
复制相似问题