-1

I use a javascript to convert markdown to html.

If I add <span id="printHello></span> to the markdown, after conversion, I could still use getElementById() to get the reference. However, there is one exception:

var abc = true;
<span id="printHello></span>
var def = false;

If the tag is added inside a code block, it will get escaped during the conversion. I can no longer get the element.

So I am thinking if I can add an identifier text, replacing the identifier text after the markdown has been converted to html. Like this:

var abc = true;
I_am_an_identifier
var def = false;

After converting, I get this:

<pre><code>var abc = true;
I_am_an_identifier
var def = false;
</code></pre>

So I can replace I_am_an_identifier to <span id="printHello></span>

Is it possible to replace by means of contents?

Liam
  • 27,717
  • 28
  • 128
  • 190
tom
  • 1,302
  • 1
  • 16
  • 30
  • 1
    What are you trying to accomplish? I don't get what you're going for... – James Hill May 09 '16 at 15:50
  • [How to get the entire document HTML as a string?](http://stackoverflow.com/questions/817218/how-to-get-the-entire-document-html-as-a-string) – Ronnie Royston May 09 '16 at 15:51
  • I was about to tell you to use regexp but, [you know...](http://stackoverflow.com/a/1732454/5054380) – Bald Bantha May 09 '16 at 15:53
  • In your example, you *could* get the content of the `span` if its ID had a closing quote, even if it's within a `code` element: https://jsfiddle.net/07qpd5mk/ – Rick Hitchcock May 09 '16 at 15:54
  • @JamesHill I am doing some real-time preview of markdowns with external editor. I need to trace the editor cursor position so that I can implement auto scroll. I add an empty tag to indicate cursor position. The problem occurs when the cursor is in a code block. – tom May 09 '16 at 16:06
  • use javascript labels I'm pretty sure your convertor will not strip them down too. Than use your html injector routine to replace the identifier with your span. – Bekim Bacaj May 09 '16 at 20:45

2 Answers2

0

Answer for your question is, you can replace a string in your HTML with another using the replace method.

document.body.innerHTML = document.body.innerHTML.replace('I_am_an_identifier', '<span id="printHello"></span>');

Note that this will replace the first instance of I_am_an_identifier, including any instances in your HTML code (e.g. class names etc..), so use with caution.

To replace all instances of the target string, use a simple regular expression with the global flag:

document.body.innerHTML = document.body.innerHTML.replace(/I_am_an_identifier/g, '<span id="printHello"></span>');
Munawir
  • 3,346
  • 9
  • 33
  • 51
0

Javascript has Labels

Fortunately you can use your identifier keyword, ( let's say you chose "printHello" ) in form of a JavaScript Label:

<pre><code>var abc = true;
printHello: 
var def = false;
</code></pre>

than you can find and replace it with whichever thing you like.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26