gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:49:08 24 4
gpt4 key购买 nike

其实我有一个奇怪的需求。这里我有 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>

那么等效的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';

这样我们就可以在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>

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

最佳答案

这将从文本区域获取输入并创建可变代码。它根据需要转义反斜杠和引号:

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>

关于javascript - 将 HTML 代码转换为 Javascript 变量(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com