-2

Regular expression not working correctly. I need to mark part of string, but I don't know how it is do

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

Ihor Stoner
  • 109
  • 4

1 Answers1

1

I think the below example works, except the first case which doesn't produce the same result, because it's not clear what the desired behaviour is when there are commas in the input.

Also:

  1. Don't forget to escape the dynamic values used in a RegExp
  2. Don't forget to 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
Anton Podolsky
  • 841
  • 2
  • 11