首页 > 解决方案 > 如何突出显示字符串中的文本?

问题描述

我有这种字符串 "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>

我在哪里做错了?

标签: javascriptregexstringreactjs

解决方案


用于(.*?)创建一个在哈希之间非贪婪地匹配任何内容的组,然后传递一个箭头函数作为第二个参数来访问匹配的组并返回替换它的值。可以在此箭头函数的第二个参数中访问该组:

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;
}


推荐阅读