javascript - 如何突出显示字符串中的文本?
问题描述
我有这种字符串 "Hello , I'm looking for /# job as a teacher #/" 。/# ----#/ 中的所有内容都必须突出显示。
这是我在做什么:
highlightMessage(message) {
if (message.match(/\/#\s*|\s*#\//g)) {
console.log(message.replace(/\/#\s*|\s*#\//g, `<span className='yellow'>$1</span>`))
}
}
但我的输出是:
Hello , I'm looking for <span className='yellow'>$1</span>job as a teacher<span className='yellow'>$1</span>
我在哪里做错了?
解决方案
用于(.*?)
创建一个在哈希之间非贪婪地匹配任何内容的组,然后传递一个箭头函数作为第二个参数来访问匹配的组并返回替换它的值。可以在此箭头函数的第二个参数中访问该组:
function highlight(message) {
return message.replace(/\/#\s*(.*?)\s*#\//g,
(_, g) => `<span className='yellow'>${g}</span>`);
}
如果需要,您甚至可以将替换函数作为参数传递以自定义替换。
这是一个在同一字符串中进行多次替换的示例:
function highlight(message, replacer = s => `<span class="bold">${s}</span>`) {
return message.replace(/\/#\s*(.*?)\s*#\//g, (_, g) => replacer(g));
}
document.body.innerHTML += highlight("Hello , /#I'm#/ looking for /# job as a teacher #/");
document.body.innerHTML += highlight("<br>Nothing to replace here");
document.body.innerHTML += highlight("<br>You can pass a custom /#replacer function #/ too", s => '' + s.toUpperCase() + '');
.bold {
font-weight: bold;
font-size: 20px;
}
推荐阅读
- python - 如何使用符号表示数据帧操作?
- mysql - 检查弱实体是否在其记录列表中包含特定值
- excel - 连接来自 2 个不同工作表的数据所需的 Excel 公式
- javascript - 道具改变时覆盖内部状态
- java - 使用IBM web sphere 8.5在struts2中实现石英调度程序,找不到JNDI名称异常
- database - 如何访问在 Heroku 中所做的文件数据更改?
- postgresql - MacOS High Sierra 卸载所有 Postgres
- javascript - 有人可以帮我将 JavaScript 策略属性/方法转换为构造函数吗?
- python - 如何将 Dask 的仪表板图直接嵌入到 JupyterLab 窗格中
- android - 挂起方法调用未执行后协程范围内的代码行