Dean Christian Armada
Dean Christian Armada

Reputation: 7384

Escape less than and greater than in HTML

content = '5<x<div></div>'

Basically I am looking for a regular expression that will make the string like above into 5&lt;x<div></div>

5x<div></div> will still be 5x<div></div>. I am just trying to escape unclosed html tags

If there is such a library then I will be very happy to use it as long as it meets my main goal of trying to escape unclosed html tags

Upvotes: 4

Views: 1518

Answers (1)

54ka
54ka

Reputation: 3589

  1. Rewrite each open tag character "<" with the symbol + unique value ... in this case ",,#*&,,"
  2. Split the string at the unique value
  3. The "replaceString ()" function checks if the passed value is really a tag ... whether both "<" and ">" characters are present in the string. If not present, rewrite the character with "& lt;".
  4. The whole process is repeated for the symbol ">"

This is not the most beautiful solution to this task but it works.

var str = '5<x<div>s>7</div>';

for (var i = 0; i < 2; i++) {
    if (i === 0) {
        var str2 = str.replace(/</gi, ",,#*&,,<");
        var spl = str2.split(",,#*&,,");
    } else {
        var str2 = str.replace(/>/gi, ">,,#*&,,");
        var spl = str2.split(",,#*&,,");
    }
    replaceString(spl);
}

function replaceString(spl) {
    for (let i = 0; i < spl.length; i++) {
        if (spl[i].indexOf('<') > -1 && spl[i].indexOf('>') > -1) {
            //.......
        } else {
            if (spl[i].indexOf('<') > -1) {
                spl[i] = spl[i].replace(/</gi, "&lt;");
            }
            else if (spl[i].indexOf('>') > -1) {
                spl[i] = spl[i].replace(/>/gi, "&gt;");
            }
        }
    }
    str = spl.join('');
}

console.log(str);

Upvotes: 1

Related Questions