0

I have an application where users can write comments containing HTML code, which is escaped before displaying:

<div class="card-body">
 <p class="card-text">
  &lt;h1&gt;HOLA&lt;/h1&gt; Cita:#2&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt; Cita:#6&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt; 
 </p>
</div>

But when a user write a specific word like "Cita:#1" I want to transform it with jQuery to a link, so later I can load an Ajax popup there with this code:

$('.card-text').each(function() {
    $(this).html($(this).text().replace(/Cita:#(\d+)/ig, '<a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#$1</a>'));
});

My problem is that it does it well but also transform all possible HTML tags inside that comment too.

Is there a way to just ignore all tags that can be inside the comment and only replace the word "Cita:#1" with a link and made it works?

Actual:

enter image description here

Expected:

enter image description here

0

1 Answer 1

1

Since you control the server-side here, this would be much easier to do in PHP:

$string = '<h1>HOLA</h1> Cita:#2<h1>HOLA</h1> <h1>HOLA</h1> Cita:#6<h1>HOLA</h1> <h1>HOLA</h1>';
$string = htmlspecialchars($string);
$string = preg_replace(
    '/Cita:#(\\d+)/i',
    '<a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#$1</a>',
    $string
);
echo $string;

Output:

&lt;h1&gt;HOLA&lt;/h1&gt; <a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#2</a>&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt; <a href="#" title="Header" data-toggle="popover" data-trigger="hover" data-content="Some content">Cita:#6</a>&lt;h1&gt;HOLA&lt;/h1&gt; &lt;h1&gt;HOLA&lt;/h1&gt;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks that one worked fine, just created a middleware and replaced the input message like u did

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.