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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33409288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:27:00  来源:igfitidea点击:

convert HTML code to Javascript variable (string)

javascripthtmlruby-on-railsruby

提问by pramod

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

其实我有一个奇怪的要求。这里我有 HTML 代码,我必须将此代码传递给 document.write 函数。为了实现这一点,我应该将该代码转换为 javascript 变量并将该代码传递给 document.write。让我用一个例子来解释它。假设我们有以下 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. 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.

事实上,为了获取 JavaScript 变量,我使用了在线转换工具。但是,我决定手动将我的 HTML 代码转换为 sting。所以我想知道我们如何用 JavaScript 或任何其他语言来做到这一点。实际上,我是一名 Ruby on Rails 开发人员,所以我想知道是否有一种简单的方法可以在 ruby​​ 中手动完成。

回答by Rick Hitchcock

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>

回答by Nishanth

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

方法一去掉换行符,使整个字符串成为一行

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

Method 2Escape 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

回答by Richard Peck

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 unescapewith the returned data from encodeMyHtml

如果要返回格式正确的 HTML,请使用unescapeencodeMyHtml



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 hack,解释如何将 HTML 转换为 JS 编码的字符串等。