Replace by ignoring tag and returning as string

Asked

Viewed 246 times

0

I think I’ve seen this problem here once, but I couldn’t find it at all, even searching the Internet (I forgot what words to use in the search because I think I’ve dealt with it before but gave me a total blank).

I’m making a replace of a text in a div and inserting a few words between the tags <b></b>.

For example:

<div id="texto">
    Qualquer texto aqui
</div>

I want the word "text" to go between <b></b> (bold):

var texto_original = $("#texto").text();
$("#texto").text(texto_original.replace("texto","<b>texto</b>"));

It turns out that after the replace the text in div gets like this:

Qualquer <b>texto</b> aqui

When the desired would be so:

Whichever text here

Take the example:

var texto_original = $("#texto").text();
$("#texto").text(texto_original.replace("texto","<b>texto</b>"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="texto">
   Qualquer texto aqui
</div>

That is, the tag is being treated as string. If I’m not mistaken there is a method that does this conversion, but I’m not remembering at all. How do you fix it?

1 answer

4


To be treated as html it has to be assigned with the function html:

var texto_original = $("#texto").html();
$("#texto").html(texto_original.replace("texto","<b>texto</b>"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="texto">
   Qualquer texto aqui
</div>

The idea of text is precisely this, to prevent what is placed as content from being interpreted as html. If the user introduces the content, the text ends up protecting against javascript injection.

  • Putz!!! That’s right!! rsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.