Hướng dẫn convert html special characters to text javascript - chuyển đổi các ký tự đặc biệt html sang javascript văn bản

Tôi biết có những thư viện ngoài kia, nhưng đây là một vài giải pháp cho trình duyệt. Chúng hoạt động tốt khi đặt chuỗi dữ liệu thực thể HTML vào các khu vực có thể chỉnh sửa của con người, nơi bạn muốn các ký tự được hiển thị, chẳng hạn như Textarea hoặc đầu vào [type = text].

Tôi thêm câu trả lời này vì tôi phải hỗ trợ các phiên bản cũ hơn của IE và tôi cảm thấy rằng nó kết thúc một vài ngày để nghiên cứu và thử nghiệm. Tôi hy vọng ai đó thấy điều này hữu ích.

Đầu tiên, đây là dành cho các trình duyệt hiện đại hơn bằng cách sử dụng jQuery, xin lưu ý rằng điều này không nên được sử dụng nếu bạn phải hỗ trợ các phiên bản IE trước 10 [7, 8 hoặc 9] của văn bản.

if [!String.prototype.HTMLDecode] {
    String.prototype.HTMLDecode = function [] {
            var str = this.toString[],
            $decoderEl = $[''];

        str = $decoderEl.html[str]
            .text[]
            .replace[//gi, "\r\n"];

        $decoderEl.remove[];

        return str;
    };
}

Điều này tiếp theo dựa trên công việc của Kennebec ở trên, với một số khác biệt chủ yếu là vì lợi ích của các phiên bản IE cũ hơn. Điều này không yêu cầu jquery, nhưng vẫn yêu cầu trình duyệt.

if [!String.prototype.HTMLDecode] {
    String.prototype.HTMLDecode = function [] {
        var str = this.toString[],
            //Create an element for decoding            
            decoderEl = document.createElement['p'];

        //Bail if empty, otherwise IE7 will return undefined when 
        //OR-ing the 2 empty strings from innerText and textContent
        if [str.length == 0] {
            return str;
        }

        //convert newlines to =0;i--] {
				buf.unshift[['&#', str[i].charCodeAt[], ';'].join['']];
			}
			
			return buf.join[''];
		},
		/**
		 * Converts an html characterSet into its original character.
		 *
		 * @param {String} str htmlSet entities
		 **/
		decode : function[str] {
			return str.replace[/&#[\d+];/g, function[match, dec] {
				return String.fromCharCode[dec];
			}];
		}
	};
}][window];

Mã trước đó tạo ra một biến toàn cầu [trong cửa sổ] có tên HTMLEntities. Đối tượng này chứa 2 Phương thức mã hóa và giải mã.

Để chuyển đổi một chuỗi bình thường thành các ký tự HTML của nó, hãy sử dụng phương thức mã hóa:

htmlentities.encode["Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html characters."];
// Output
"Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html characters."

Để chuyển đổi chuỗi HTML được mã hóa thành các ký tự có thể đọc được, hãy sử dụng phương thức giải mã:

htmlentities.decode["Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html characters."];
// Output
"Hello, this is a test stríng > < with characters that could break html. Therefore we convert it to its html characters."

Lưu ý: Hãy thoải mái sao chép mọi chức năng và đưa nó vào dự án của bạn như bạn muốn. feel free to copy every single function and include it in your project as you wish.

Sử dụng một thư viện

Là một nhiệm vụ không dễ đạt được, có một thư viện tuyệt vời sẽ giải quyết vấn đề này cho bạn.

He.js & nbsp; [đối với các thực thể HT HTML] là một bộ mã hóa/bộ giải mã thực thể HTML mạnh mẽ được viết bằng JavaScript. Nó hỗ trợ tất cả các tài liệu tham khảo ký tự được tiêu chuẩn hóa theo HTML, xử lý các ampersand mơ hồ và các trường hợp cạnh khác giống như trình duyệt, có một bộ thử nghiệm rộng rãi và trái với nhiều giải pháp JavaScript khác, & NBSP; anh ta xử lý các biểu tượng Unicode. Một bản demo trực tuyến có sẵn. [for “HTML entities”] is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and contrary to many other JavaScript solutions, he handles astral Unicode symbols just fine. An online demo is available.

Mã hóa

Hàm này lấy một chuỗi văn bản và mã hóa [theo mặc định] bất kỳ biểu tượng nào có thể in các ký hiệu ASCII và ____10,

if [!String.prototype.HTMLDecode] {
    String.prototype.HTMLDecode = function [] {
        var str = this.toString[],
            //Create an element for decoding            
            decoderEl = document.createElement['p'];

        //Bail if empty, otherwise IE7 will return undefined when 
        //OR-ing the 2 empty strings from innerText and textContent
        if [str.length == 0] {
            return str;
        }

        //convert newlines to  to save them
        str = str.replace[/[[\r\n]|[\r]|[\n]]/gi, " 
"]; decoderEl.innerHTML = str; /* We use innerText first as IE strips newlines out with textContent. There is said to be a performance hit for this, but sometimes correctness of data [keeping newlines] must take precedence. */ str = decoderEl.innerText || decoderEl.textContent; //clean up the decoding element decoderEl = null; //replace back in the newlines return str.replace[//gi, "\r\n"]; }; } /* Usage: var str = ">"; return str.HTMLDecode[]; returned value: [String] > */
4 và
if [!String.prototype.HTMLDecode] {
    String.prototype.HTMLDecode = function [] {
        var str = this.toString[],
            //Create an element for decoding            
            decoderEl = document.createElement['p'];

        //Bail if empty, otherwise IE7 will return undefined when 
        //OR-ing the 2 empty strings from innerText and textContent
        if [str.length == 0] {
            return str;
        }

        //convert newlines to  to save them
        str = str.replace[/[[\r\n]|[\r]|[\n]]/gi, " 
"]; decoderEl.innerHTML = str; /* We use innerText first as IE strips newlines out with textContent. There is said to be a performance hit for this, but sometimes correctness of data [keeping newlines] must take precedence. */ str = decoderEl.innerText || decoderEl.textContent; //clean up the decoding element decoderEl = null; //replace back in the newlines return str.replace[//gi, "\r\n"]; }; } /* Usage: var str = ">"; return str.HTMLDecode[]; returned value: [String] > */
0,
if [!String.prototype.HTMLDecode] {
    String.prototype.HTMLDecode = function [] {
        var str = this.toString[],
            //Create an element for decoding            
            decoderEl = document.createElement['p'];

        //Bail if empty, otherwise IE7 will return undefined when 
        //OR-ing the 2 empty strings from innerText and textContent
        if [str.length == 0] {
            return str;
        }

        //convert newlines to  to save them
        str = str.replace[/[[\r\n]|[\r]|[\n]]/gi, " 
"]; decoderEl.innerHTML = str; /* We use innerText first as IE strips newlines out with textContent. There is said to be a performance hit for this, but sometimes correctness of data [keeping newlines] must take precedence. */ str = decoderEl.innerText || decoderEl.textContent; //clean up the decoding element decoderEl = null; //replace back in the newlines return str.replace[//gi, "\r\n"]; }; } /* Usage: var str = ">"; return str.HTMLDecode[]; returned value: [String] > */
2,
if [!String.prototype.HTMLDecode] {
    String.prototype.HTMLDecode = function [] {
        var str = this.toString[],
            //Create an element for decoding            
            decoderEl = document.createElement['p'];

        //Bail if empty, otherwise IE7 will return undefined when 
        //OR-ing the 2 empty strings from innerText and textContent
        if [str.length == 0] {
            return str;
        }

        //convert newlines to  to save them
        str = str.replace[/[[\r\n]|[\r]|[\n]]/gi, " 
"]; decoderEl.innerHTML = str; /* We use innerText first as IE strips newlines out with textContent. There is said to be a performance hit for this, but sometimes correctness of data [keeping newlines] must take precedence. */ str = decoderEl.innerText || decoderEl.textContent; //clean up the decoding element decoderEl = null; //replace back in the newlines return str.replace[//gi, "\r\n"]; }; } /* Usage: var str = ">"; return str.HTMLDecode[]; returned value: [String] > */
4, and
if [!String.prototype.HTMLDecode] {
    String.prototype.HTMLDecode = function [] {
        var str = this.toString[],
            //Create an element for decoding            
            decoderEl = document.createElement['p'];

        //Bail if empty, otherwise IE7 will return undefined when 
        //OR-ing the 2 empty strings from innerText and textContent
        if [str.length == 0] {
            return str;
        }

        //convert newlines to 

Bài Viết Liên Quan

Chủ Đề