I need to replace less or greater than(< >) characters, but keep any html tags(simple tags will do like <b>text</b> without arguments).
So the input below:
<b>> 0.5 < 0.4</b> - <>
Should be:
<b>> 0.5 < 0.4</b> - <>
All I managed to find and edit now is this expr:
<\/?[a-z][a-z0-9]*[^>\s]*>|([<>])
It groups the < and > characters but it also matches tags witch I don't need to replace
UPD: Thanks to @Sree Kumar, here's the final functions:
String.prototype.replaceAt = function (index, char) {
let arr = this.split('');
arr[index] = char;
return arr.join('');
};
String.prototype.escape = function () {
let p = /(?:<[a-zA-Z]+>)|(?:<\/[a-zA-Z]+>)|(?<lt><)|(?<gt>>)/g,
result = this,
match = p.exec(result);
while (match !== null) {
if (match.groups.lt !== undefined) {
result = result.replaceAt(match.index, '<');
}
else if (match.groups.gt !== undefined) {
result = result.replaceAt(match.index, '>');
}
match = p.exec(result);
}
return result;
};
.replace(/<\s*\/?\s*\w+\s*\/?\s*>|(<)|(>)/g, (m, g1, g2) => g2 ? '>' : g1 ? '<' : m)might work. Or.replace(/<\s*\/?\s*\w+[^>]*>|(<)|(>)/g, (m, g1, g2) => g2 ? '>' : g1 ? '<' : m). This is not precise, but might be enough. To make it more precise you will need to list the tags, to avoid matching<my_word>like strings.null, discard it.