0

I want to format user input on client side only and replace &lt;br/&gt; that returned from server to <br/> html element.

I have the below javascript code to format user input

function HtmlEncode(s){
  var el = document.createElement("div");
  el.innerText = el.textContent = s;
  s = el.innerHTML;
  return replace_chat_tags(s);
}

I use the below function to replace url and email from client

function replace_chat_tags(chat_body = '') {
  return chat_body
    .replace( /((http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?=\-&_/]+)/g, "<a href=\"$1\" target=\"_blank\">$1</a>" )
    .replace( /\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b/gi, "<a href=\"mailto:$1\">$1</a>" )
    .replace( /&lt;br\/&gt;/g, "<br/>" );
}

My problem is the above code doesn't replace &lt; and &gt; when it match it still return &lt;br\/&gt;, Can somebody give me a hint on this? HtmlEncode(chat.message)

assembler
  • 3,098
  • 12
  • 43
  • 84
Peter
  • 1,860
  • 2
  • 18
  • 47

1 Answers1

1

The Regex should be constructed properly.

k = "&lt;br/&gt"

console.log(k.replace(new RegExp("&lt;br/&gt", "g"), "<br/>"));

console.log(k.replace(new RegExp(/&lt;br\/&gt/, "g"), "<br/>"));
Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36