1

I know it's going to be a VERY obvious answer, but I can't find anything on how to do this.

I'm trying to unescape < and > within an HTML string

My test output string is essentially:

```php
&gt;h2&lt;Heading2&gt;/h2&lt;
```

`&gt;h2&lt;Heading2&gt;/h2&lt;`

&gt;h2&lt;Heading2&gt;/h2&lt;

So in this example we have Github flavoured Markdown, a regular code markdown snippet, and then raw text all with the same HTML tag. I want to unescape the raw tag (the third one) to actually become a link. The ideal output would be something like this.

```php
&gt;h2&lt;Heading2&gt;/h2&lt;
```

`&gt;h2&lt;Heading2&gt;/h2&lt;`

<h2>Heading2</h2>

I'm getting stuck at getting multiple &gt; in the same line.

Current regex:

/(?:.*?(&gt;))/

This will get the first entry.

/(?:.*?(&gt;))/g

This one gets the second entry. I want it to be able to get EVERY entry. Then, it's just a matter of throwing the tick pieces.

/(?:```|`)(?:.*?(&gt;)).*?(?:```|`)/gs
1
  • I can only replace the &gt; that are NOT within ```{here}``` and `{here}` Commented Feb 6, 2015 at 21:25

1 Answer 1

2

If you're intending on using a regular expression for this task, you can consider the following:

var r = s.replace(/((`(?:``)?)[^`]*\2)|&gt;/g, '$1<')
         .replace(/((`(?:``)?)[^`]*\2)|&lt;/g, '$1>')
         .replace(/`[<>]+/g, '`');

Working Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks hwnd! May I ask why the second replace is necessary? I see the issue, but I'm wondering if we can get it to not add the < after the trailing tick.
Either way, this will solve it I think, and just run a second with &lt; replaced by $1>
Thanks so much! I may end up switching to using AJAX and using my PHP parser, as it's much more complete, but this will work great for now, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.