Home  >  Article  >  Web Front-end  >  How to convert html to string

How to convert html to string

PHPz
PHPzOriginal
2023-04-21 14:13:104260browse

In web page production and development, we often need to convert HTML code into string format to facilitate transmission, storage, operation, etc. Next, we will explore how to convert HTML into strings.

1. Use the escape function

escape is a built-in function of JavaScript that can convert non-ASCII characters in a string into %xx form. When processing HTML code, we can use escape to convert the HTML code into string format.

Sample code:

var html = "<div>这是一段HTML代码</div>";
var str = escape(html);
console.log(str); // %3Cdiv%3E%E8%BF%99%E6%98%AF%E4%B8%80%E6%AE%B5HTML%E4%BB%A3%E7%A0%81%3C%2Fdiv%3E

Note: The string converted using escape needs to be converted back to the original HTML code using the unescape function.

2. Use the encodeURIComponent function

encodeURIComponent is a built-in function of JavaScript that can convert special characters in a string into %xx form. When processing HTML code, we can use encodeURIComponent to convert the HTML code into string format.

Sample code:

var html = "<div>这是一段HTML代码</div>";
var str = encodeURIComponent(html);
console.log(str); // %3Cdiv%3E%E8%BF%99%E6%98%AF%E4%B8%80%E6%AE%B5HTML%E4%BB%A3%E7%A0%81%3C%2Fdiv%3E

Note: The string converted using encodeURIComponent needs to be converted back to the original HTML code using the decodeURIComponent function.

3. Use the innerHTML attribute

The innerHTML attribute of an element in HTML can get or set the HTML content of the element. We can get the HTML code through the innerHTML attribute, and then use the JSON.stringify() function to convert it into string format.

Sample code:

var html = "<div>这是一段HTML代码</div>";
var div = document.createElement("div");
div.innerHTML = html;
var str = JSON.stringify(div.innerHTML);
console.log(str); // "\"<div>这是一段HTML代码</div>\""

Note: The converted string will have quotes, we need to use the eval() function to convert it back to the original HTML code.

Summary

The above are three ways to convert HTML code into string format. Each method has its advantages and disadvantages, and we can choose the appropriate method according to the specific situation. When using it, you also need to note that the converted string needs to be reverse-converted back to the original HTML code.

The above is the detailed content of How to convert html to string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to develop HTMLNext article:How to develop HTML