Last active
October 29, 2018 04:19
-
-
Save madprops/93c40e0c1e08a147d5cbe1bda0d47a1b to your computer and use it in GitHub Desktop.
This function can be used to use html characters for tags (< and >) inside tags that you specify.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For instance: | |
// If s = <code><code>This is a nested code that should be replaced</code> <div>Any tag here is replaced</div></code> | |
// safeparse(s, "code", "code") returns: | |
// <code><code>This is a nested code that should be replaced</code> <div>Any tag here is replaced</div></code> | |
// It should work for any number of correctly written nests. | |
// This will be applied to all specified top level tags. | |
// chars is the text to be parsed | |
// s1 is the starting tag | |
// s2 is the closing tag | |
function safeparse(chars, s1, s2) | |
{ | |
function replace_string_at(s, c, i, i2=false) | |
{ | |
var ns1 = s.slice(0, i) | |
var ns2 | |
if(i2) | |
{ | |
ns2 = s.slice(i2, s.length) | |
} | |
else | |
{ | |
ns2 = s.slice(i + 1, s.length) | |
} | |
return ns1 + c + ns2 | |
} | |
s2 = `/${s2}` | |
var s1b = `<${s1}>` | |
var s2b = `<${s2}>` | |
var len1 = s1b.length | |
var len2 = s2b.length | |
let i = 0 | |
var ncode = 0 | |
while(i < chars.length) | |
{ | |
if(ncode === 0) | |
{ | |
let index = chars.indexOf(s1b, i) | |
if(index > -1) | |
{ | |
i = index + len1 | |
ncode += 1 | |
} | |
else | |
{ | |
break | |
} | |
} | |
else if(ncode > 0) | |
{ | |
let index = chars.indexOf("<", i) | |
let index2 = chars.indexOf(">", i) | |
if(index > -1) | |
{ | |
if(chars.slice(index, index + len1) === s1b) | |
{ | |
chars = replace_string_at(chars, `<${s1}>`, index, index + len1) | |
ncode += 1 | |
i = index + len1 | |
index2 = -1 | |
} | |
else if(chars.slice(index, index + len2) === s2b) | |
{ | |
if(ncode > 1) | |
{ | |
chars = replace_string_at(chars, `<${s2}>`, index, index + len2) | |
} | |
ncode -= 1 | |
if(ncode < 0) | |
{ | |
ncode = 0 | |
} | |
i = index + len2 | |
index2 = -1 | |
} | |
else | |
{ | |
chars = replace_string_at(chars, "<", index) | |
i = index + 4 | |
index2 = chars.indexOf(">", i) | |
} | |
} | |
if(index2 > -1) | |
{ | |
if(index2 < index || ncode > 0) | |
{ | |
chars = replace_string_at(chars, ">", index2) | |
i = Math.max(index2 + 4, i) | |
} | |
} | |
if(index < 0 && index2 < 0) | |
{ | |
break | |
} | |
} | |
} | |
return chars | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment