Replace characters [duplicate]

1

This post may seem duplicated, but I have tried several ways and the problem is not solved.

I have a DataTable in which I dynamically load HTML tags.

These labels, instead of being like this:

<img src="ruta" />

they look like this:

&lt;img  src="ruta"/&gt;

I have made a jquery script that replaces the characters &lt; and &gt; with < and > respectively.

The problem is that only the first appearance replaces me, leaving a message like this:

 <img  src="ruta"/> &lt;img  src="ruta"/&gt; &lt;img  src="ruta"/&gt; &lt;img  src="ruta"/&gt;

My Jquery code is as follows

$(".message").each(function(){
            var $this = $(this);
            var t = $this[0].innerHTML;
            $this.html(t.replace('&lt;','<').replace('&gt;', '>'));
        });

My HTML looks like this:

<div class="message">&lt;img  src="ruta"/&gt; &lt;img  src="ruta"/&gt; </div>

That div is part of a row of a datatable.

How could I make Datatable render the HTML tags or have JQUERY replace the characters in ALL the messages instead of just the first one.

Thank you.

    
asked by XBoss 26.07.2018 в 12:26
source

1 answer

1

You have almost done it, what you were missing was to use a regular expression with the global modifier ( g )

const original='&lt;img  src="ruta"/&gt; &lt;img  src="ruta"/&gt; ';

const cambiado=original.replace(/&lt;/g,'<').replace(/&gt;/g,'>');
console.log(cambiado)

Small explanation: The replace method supports as a first parameter a string causing the substitution of the first match or a regular expression. In the case of regular expression, you can define certain modifiers.

Here is an example:

const miExpReg= /a/gi;

console.log('Aquí hay letras mAyúsculas y minúsculas'.replace(miExpReg,'_'));

g - > global ( all matches ) i - > ignore uppercase / lowercase

    
answered by 26.07.2018 / 13:14
source