javascript - 给字符串加粗

标签 javascript jquery

我有一个带有线条的简单跨度。我只想将包含 Running test: 的行加粗。 所有线路

<span id="results" style="white-space: pre-line">Running test: test1
asasggsa
fasfs
afasaggas
</span>

知道怎么做吗?

应该是这样的

 <span id="results" style="white-space: pre-line"><strong>Running test: test1</strong>
    asasggsa
    fasfs
    afasaggas
    </span>

最佳答案

使用拆分合并

演示

var value = results.innerHTML; //since results is an id
var textToBold = value.split( "\n" )[0]; //get the first line
results.innerHTML = value.split( textToBold ).join( "<strong>" + textToBold + "</strong>" ); //split by the text to bold and then join with enclosing tags
<span id="results" style="white-space: pre-line">Running test: test1
asasggsa
fasfs
afasaggas
</span>

I just want to bold the line that contains Running test:. All line

在这种情况下使用匹配

演示

var value = results.innerHTML; //since results is an id
var text = "Running test";
var linesToBold = value.split( "\n" ).map( s => s.includes( text ) ?  "<strong>" + s + "</strong>" : s ).join( "\n" );
results.innerHTML = linesToBold
<span id="results" style="white-space: pre-line">Running test: test1
asasggsa
fasfs
afasaggas
</span>

关于javascript - 给字符串加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49237056/

相关文章:

Javascript使用RegEXP删除特殊字符之间(但不包括)的字符

javascript - HTML 头文件,改变按钮状态

javascript - 使用复选框 onClick 覆盖父级 onClick 事件?

javascript - jquery-confirm - 以多个按钮的形式提交点击按钮

javascript - 如何在同位素排序后更新编号的 div?

javascript - 想添加下拉列表

Javascript,单击所有图像时打印消息

javascript - 组合对象值

javascript - jQuery 通过单击链接来排列 li 顺序

javascript - 如何在 chart.js 中的图例项上显示工具提示