Пример изоляции ссылок

https://toster.ru/q/361449

by Aleksey Nemiro

HTML

<div id="result"></div>

JavaScript

function replaceStandardHtmlEntities(text) {
  // маскируем ссылки
  // понятный вариант
  // text = text.replace(/\<a([^\>]*)\>/g, '[a$1]');
  // text = text.replace(/\<\/a\>/g, '[/a]');
  // а здесь используется символ с кодом 1, 
  // чтобы не пересекать с реальными последовательностями (типа [a] как выше)
  text = text.replace(/\<a([^\>]*)\>/g, String.fromCharCode(1) + 'a$1' + String.fromCharCode(1));
  text = text.replace(/\<\/a\>/g, String.fromCharCode(1) + '/a' + String.fromCharCode(1));
    
  // остальной код без изменений
  let regular = /( {2}|&|'|<|>|\\n)/g, translate = {
    '  ': '&nbsp',
    '&': '&amp',
    '\'': '&quot',
    '<': '&lt',
    '>': '&gt',
    '\\n': '<br>'
  };

  // результат замены передаем в переменную
  let result = (text.replace(regular, (match, entity) => {
    return translate[entity];
  }));
  
  // возвращаем ссылки обратно
  // result = result.replace(/\[a([^\]]*)\]/g, '<a$1>');
  // result = result.replace(/\[\/a\]/g, '</a>');
  result = result.replace(/\x01a([^\x01]*)\x01/g, '<a$1>');
  result = result.replace(/\x01\/a\x01/g, '</a>');
  
  return result;
}

document.getElementById('result').innerHTML = replaceStandardHtmlEntities('<Hello> "world" & all <a href="http://example.org">space</a>');