如何突出显示字符串中的文字?

问题描述 投票:2回答:2

我有这种字符串“你好,我正在寻找/#作为老师的工作#/”。这个/#----#/中的所有内容都必须突出显示。

我在做什么:

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>

我在哪里做错了?

javascript regex string reactjs
2个回答
2
投票

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

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

0
投票

您可以使用正则表达式\/#(.*)#\//# #/中的所有内容转换为捕获组,并使用replace包装器将<span>放入其中。

function highlightMessage(message) {
  if (/\/#.*#\//g.test(message)) {
    document.body.innerHTML += message.replace(/\/#(.*)#\//g, `<span class='red'>$1</span>`)
  }
}

highlightMessage("Hello , I'm looking for /# job as a teacher #/")
.red { color: red }
<body></body>

class用于代替className用于演示目的)

© www.soinside.com 2019 - 2024. All rights reserved.