admin管理员组

文章数量:1389352

I am copying the "view source" of an external html page (1.html) into a variable in javascript in another html page (2.html). But due to the indentation, quotes, spaces and tags in the html page, i am not able to store all of the source code in the string at one go. Is there any function which can be used to do so?

Contents of 1.html:

<html>
<head>
    <title>1 </title>
</head>
<body>
    This is just plain text body
    <div id="new"> This id div text</div>
    <span> This is span text </span>
</body>
</html>

Contents of 2.html:

<html>
<head>
<script type="text/javascript" language="javascript">
var str="<html>
<head>
    <title>2 </title>
</head>
<body>
    This is just plain text body
    <div id="new"> This id div text</div>
    <span> This is span text </span>
</body>
</html>";

alert (str);
</script>
</head>
<body>
</body>
</html>

if a paste all the contents copied from 1.html after var=" inside 2.html, it does not take all of it.. Any solution to this?

I am copying the "view source" of an external html page (1.html) into a variable in javascript in another html page (2.html). But due to the indentation, quotes, spaces and tags in the html page, i am not able to store all of the source code in the string at one go. Is there any function which can be used to do so?

Contents of 1.html:

<html>
<head>
    <title>1 </title>
</head>
<body>
    This is just plain text body
    <div id="new"> This id div text</div>
    <span> This is span text </span>
</body>
</html>

Contents of 2.html:

<html>
<head>
<script type="text/javascript" language="javascript">
var str="<html>
<head>
    <title>2 </title>
</head>
<body>
    This is just plain text body
    <div id="new"> This id div text</div>
    <span> This is span text </span>
</body>
</html>";

alert (str);
</script>
</head>
<body>
</body>
</html>

if a paste all the contents copied from 1.html after var=" inside 2.html, it does not take all of it.. Any solution to this?

Share Improve this question asked Feb 29, 2012 at 11:00 user1196522user1196522 2713 gold badges4 silver badges7 bronze badges 2
  • 2 Why would you want to do this? – Felix Kling Commented Feb 29, 2012 at 11:03
  • to pare against changes, in html – Muhammad Umer Commented Apr 20, 2014 at 18:35
Add a ment  | 

2 Answers 2

Reset to default 3

You cannot store multiline text in javascript string. To store that html in javascript you have to escape quotes and remove whitespace. Some examples:

This won't work:

var str = "Multiline
Text";

This won't work either:

var str = "Non-escaped text with "double quotes" and 'single quotes'";

This will work:

var str = "This will work because the \"double quotes\" are escaped";

You forgot to escape quote :

    <div id=\"new\"> This id div text</div>

And replace new line with \n

本文标签: Store HTML code in a string in javascriptStack Overflow