简体   繁体   English

将HTML代码转换为Javascript变量(字符串)

[英]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. 这里我有HTML代码,我必须将此代码传递给document.write函数。 To achieve that I should make that code into javascript variable and pass that code to document.write. 为了实现这一点,我应该将该代码转换为javascript变量并将该代码传递给document.write。 Let me explain it with an example. 让我用一个例子解释一下。 Say if we have the below HTML code 假如我们有以下HTML代码

<!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 然后等效的JavaScript变量如下

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 这样我们就可以在document.write函数中使用这个变量,如下所示

<!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 . 的确,要获取JavaScript变量,我使用的是在线转换工具 But, I decided to convert my HTML code to sting manually. 但是,我决定手动将我的HTML代码转换为sting。 So I would like to know how we can do it in JavaScript or any other language. 所以我想知道我们如何用JavaScript或任何其他语言来做到这一点。 Actually I am a Ruby on Rails developer so I wonder that there is an easy way to do it manually in ruby. 实际上我是Ruby on Rails开发人员,所以我想知道有一种简单的方法可以在ruby中手动完成。

This will take the input from a textarea and create the variable code. 这将从textarea获取输入并创建变量代码。 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 方法1删除换行符,使整个字符串成为一行

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

Method 2 Escape the line breaks with backslashes. 方法2使用反斜杠转义换行符。

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

Method 3 : Concatenate the string a line at a time 方法3 :一次将字符串连接一行

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

Method 4 : Create an array strings and join them 方法4:创建一个数组字符串并加入它们

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 来源: Javascript document.write('HTML CODE HERE')并使用flash抓取的var

If I'm right in assuming you want to generate "encoded" HTML through JS, this resource seems to answer the question : 如果我认为你想通过JS生成“编码”HTML,那么这个资源似乎回答了这个问题

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/ 这里有一个JSFiddle: http//jsfiddle.net/m8uyhz26/2/

If you want to return properly formatted HTML, use unescape with the returned data from encodeMyHtml 如果你想返回格式正确的HTML,使用unescape从返回的数据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. 如果你给人们一个你需要转换HTML或JS等的原因,那么你将能够得到更好的答案。

As it stands, you'll get a bunch of JS hacks explaining how to turn HTML into JS-encoded strings etc. 就目前而言,您将获得一堆JS黑客,解释如何将HTML转换为JS编码的字符串等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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