Skip to content

Instantly share code, notes, and snippets.

@madprops
Last active October 29, 2018 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madprops/93c40e0c1e08a147d5cbe1bda0d47a1b to your computer and use it in GitHub Desktop.
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.
// 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>&lt;code&gt;This is a nested code that should be replaced&lt;/code&gt; &lt;div&gt;Any tag here is replaced&lt;/div&gt;</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, `&lt;${s1}&gt;`, 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, `&lt;${s2}&gt;`, index, index + len2)
}
ncode -= 1
if(ncode < 0)
{
ncode = 0
}
i = index + len2
index2 = -1
}
else
{
chars = replace_string_at(chars, "&lt;", index)
i = index + 4
index2 = chars.indexOf(">", i)
}
}
if(index2 > -1)
{
if(index2 < index || ncode > 0)
{
chars = replace_string_at(chars, "&gt;", 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