J.Ko
J.Ko

Reputation: 1051

Replaced string shows the tag in window

I replaced a part of a div (that is content editable) with a tagged word. Instead of showing just the content of that new word, it shows the tags as well.

Here's the original content of the div:

This is inside the <div> tag, and I'd like to replace this [[var12]]

This is how I'd like it to look:

This is inside the <div> tag, and I'd like to replace this var12

However, it ends up looking like this:

This is inside the <div> tag, and I'd like to replace this <span>var12</span>

This is the code that I used:

var pattern = new RegExp("\\[\\[var[0-9]*\\]\\]")
if ($(this).text().match(pattern)) {
    var match = $(this).text().match(pattern);
    var num = match.toString().match(/[0-9]+/);  
    var tagged = '<span class="variable">VAR ' + num + '</span>';
    $(this).text($(this).text().replace(pattern, tagged));    
}

Upvotes: 1

Views: 46

Answers (1)

Christian
Christian

Reputation: 19750

It looks like that because you've specifically told it to escape the html by using .text(). If you want to insert html, you can use .html().

$(this).html($(this).text().replace(pattern, tagged));

From the .text() docs:

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.

Upvotes: 4

Related Questions