regex 请帮助我使用正则表达式[已关闭]

rxztt3cl  于 2023-02-25  发布在  其他
关注(0)|答案(1)|浏览(144)

已关闭。此问题需要超过focused。当前不接受答案。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

昨天关门了。
Improve this question
正则表达式工作不正常。我需要标记字符串的一部分,但我不知道它是如何做的

const markPartOfString = (string, substrings) => {
  if (!substrings) return string;
  const parts = substrings.split(',').map(str => str.trim());

  let markedString = string;
  parts.forEach(part => {
    const regex = new RegExp(`\\b${part}\\b`, 'gi');
    markedString = markedString.replace(regex, match => `<mark>${match}</mark>`);
  });

  return markedString;
}

//Expected result 
console.log(markPartOfString("wfo test3", "wfo test, wfo test3, wf te")); // <mark>wfo</mark><mark>test3</mark>
console.log(markPartOfString("wfo test", "wf")); // <mark>wf</mark>0 test
console.log(markPartOfString("wfo test", "wf te")); // <mark>wf</mark>o <mark>te</mark>st
console.log(markPartOfString("wfo test", "wfo")); // <mark>wfo</mark> test
console.log(markPartOfString("wfo test", "o st")); // wf<mark>o</mark> <mark>st</mark>est
zzwlnbp8

zzwlnbp81#

我认为下面的例子是可行的,除了第一种情况不会产生相同的结果,因为当输入中有逗号时,不清楚所需的行为是什么。
还有:
1.别忘了escape the dynamic values used in a RegExp
1.别忘了escape the dynamic values used in HTML

// https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// https://stackoverflow.com/questions/6234773/can-i-escape-html-special-chars-in-javascript
function escapeHtml(str) {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
 }

const markPartOfString = (string, substrings) => {
  if (!substrings) return string;
  
  const parts = substrings.split(',')
    .flatMap(str => str.split(' '))
    .map(str => escapeRegExp(str.trim()))
    .filter(str => !!str);

  const regex = new RegExp(`(${parts.join('|')})`, 'gi');

  return string.replace(regex, match => `<mark>${escapeHtml(match)}</mark>`);
}

//Expected result 
console.log(markPartOfString("wfo test3", "wfo test, wfo test3, wf te")); // <mark>wfo</mark><mark>test3</mark>
console.log(markPartOfString("wfo test", "wf")); // <mark>wf</mark>0 test
console.log(markPartOfString("wfo test", "wf te")); // <mark>wf</mark>o <mark>te</mark>st
console.log(markPartOfString("wfo test", "wfo")); // <mark>wfo</mark> test
console.log(markPartOfString("wfo test", "o st")); // wf<mark>o</mark> <mark>st</mark>est

相关问题