Replace the / symbols with Javascript

Posted on

Question :

I would like to know how to replace the < /> symbols with Javascript. I’m using the <code></code> tag to display a code, but I do not want it to be rendered in the browser. I know I can use &#60; and &#62; to display a < tag / > so I would like to know if there is a way to do Javascript do this for me, look for the symbols and automatically replace them so the code is not rendered.

I know of the existence of utilities like Syntax Highlighter, but for that case I only need to display the code on a single page and I do not think it would be interesting to add it to the page.


Answer :

Tweaking HTML in this way is discouraged.
But in a controlled way test like this:

var conteudo= $('body').html(); // body ou o elemento que preferir
// apanhar comentários
conteudo = (conteudo.replace(/<!--/g, '&#60;&#33;&#45;&#45;')).replace(/-->/g, '&#45;&#45;&#62;');
// apanhar elementos
conteudo = (conteudo.replace(/</g, '&#60;')).replace(/>/g, '&#62;');
$('body').html('<pre>' + conteudo + '</pre>'); // juntei as tags <pre> para manter a formatação do código

I used replace () with a regular expression that picks up what is inside the />/g bars, and replaces it with the other parameter. The g means multiple times. If it were not just the first occurrence.

This method is destructive if applied back to the page since all tags, including <script> , <style> are overlaid.


I’ve been playing around with this idea for a while, I leave here the example .


Depending on your requirements, one option may be to use the xmp tag instead of a Javascript. It is “deprecated” but works on most browsers.

   <a href="blabla">bleble</a>
   <h1>Teste 123</h1>

A more creative option is to use a textarea off and no borders:

<textarea disabled="true" style="border: none;background-color:white; width:500px; height: 300px;">
  <a href="blabla">bleble</a>
  <h1>Teste 123</h1>

A third option (weird medium, hehe) would be to use a <iframe> referencing a text file with code.

However, I recommend that you try to change the characters (either manually or with the help of a tool), just as you already indicated. If it is a dynamic code, you can do this by using the language of your application on the server, and bring the code already formatted to the browser. For example, in PHP (beware of possible security issues, preferably ignore <script> tags):

htmlspecialchars('<h1>Teste 123</h1>')

And if it’s a static code, just use find / replace from your editor. = D


Leave a Reply

Your email address will not be published. Required fields are marked *