简体   繁体   中英

convert HTML code to Javascript variable (string)

Actually I have a strange requirement. Here I have HTML code and I have to pass this code into document.write function. To achieve that I should make that code into javascript variable and pass that code to document.write. Let me explain it with an example. Say if we have the below HTML code

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Then the equivalent JavaScript variable is as follows

var myVariable = '<!DOCTYPE html>\n<html>\n<head>\n<title>Page Title<\/title>\n<\/head>\n<body>\n\n<h1>This is a Heading<\/h1>\n<p>This is a paragraph.<\/p>\n\n<\/body>\n<\/html>\n';

So that we can use this variable in document.write function as follows

<!DOCTYPE html>
<html>
<body>

<script>
    var myVariable = '<!DOCTYPE html>\n<html>\n<head>\n<title>Page Title<\/title>\n<\/head>\n<body>\n\n<h1>This is a Heading<\/h1>\n<p>This is a paragraph.<\/p>\n\n<\/body>\n<\/html>\n';
document.write(myVariable);

</script>

</body>
</html>

Indeed, to get the JavaScript variable I am using on-line conversion tool . But, I decided to convert my HTML code to sting manually. So I would like to know how we can do it in JavaScript or any other language. Actually I am a Ruby on Rails developer so I wonder that there is an easy way to do it manually in ruby.

This will take the input from a textarea and create the variable code. It escapes backslashes and quotes as needed:

function makeVariable() {
  var code= document.getElementById('input').value.trim(),
      output= document.getElementById('output');

  output.textContent= 'var myVariable= "'+
                      code.replace(/\\/g, '\\\\')
                          .replace(/"/g, '\\"')
                          .replace(/[\n\r]/g, '\\n')+
                      '";';
}

 document.querySelector('button').addEventListener('click', makeVariable); function makeVariable() { var code= document.getElementById('input').value.trim(), output= document.getElementById('output'); output.textContent= 'var myVariable= "'+ code.replace(/\\\\/g, '\\\\\\\\') .replace(/"/g, '\\\\"') .replace(/[\\n\\r]/g, '\\\\n')+ '";'; } 
 textarea { height: 20em; width: 100%; } pre { white-space: pre-wrap; background: #246; color: white; padding: 0.2em; } 
 <button>Create variable</button> <pre id="output"></pre> <textarea id="input"> <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1 class="header">This is a Heading</h1> <p>This is a paragraph.</p> <p>This has a backslash \\.</p> </body> </html> </textarea> 

Method 1 Remove the line breaks, making the entire string a single line

var lines = '<div id="jwplayer"><center>...</center></div>';
document.write(lines);

Method 2 Escape the line breaks with backslashes.

var lines = '<div id="jwplayer">\
    <center>\
      ...\
    </center>\
  </div>';
document.write(lines);

Method 3 : Concatenate the string a line at a time

var lines = '<div id="jwplayer">';
lines += '<center>';
lines += '...';
lines += '</center>';
lines += '</div>';
document.write(lines);

Method 4 : Create an array strings and join them

var lines = [
  '<div id="jwplayer">',
  '<center>',
  '...',
  '</center>',
  '</div>'].join(' ');
document.write(lines);

Source : Javascript document.write('HTML CODE HERE') and using a var grabbed by flash

If I'm right in assuming you want to generate "encoded" HTML through JS, this resource seems to answer the question :

function OuterHTML(element) {
  var container = document.createElement("div");
  container.appendChild(element.cloneNode(true));
  return container.innerHTML;
}

function encodeMyHtml(html) {
 encodedHtml = escape(html);
 encodedHtml = encodedHtml.replace(/\//g,"%2F");
 encodedHtml = encodedHtml.replace(/\?/g,"%3F");
 encodedHtml = encodedHtml.replace(/=/g,"%3D");
 encodedHtml = encodedHtml.replace(/&/g,"%26");
 encodedHtml = encodedHtml.replace(/@/g,"%40");
 return encodedHtml;
} 

So you'd be able to call ( referencing this answer ):

div = document.getElementById('jwplayer');
encoded = encodeMyHtml(div);

Here's a JSFiddle for you: http://jsfiddle.net/m8uyhz26/2/

If you want to return properly formatted HTML, use unescape with the returned data from encodeMyHtml


The main issue you have is lack of context in your question. If you gave people a reason why you need to convert HTML or JS etc, you'd be able to receive better answers.

As it stands, you'll get a bunch of JS hacks explaining how to turn HTML into JS-encoded strings etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM