HTML可以't按原样显示或根本不显示

exhaustive list of all character patterns that HTML can't display as is or not display at all

本文关键字:显示 按原样 可以 HTML      更新时间:2023-09-26

我的web应用程序中有一个要求,即按原样显示从服务器接收的字符串。当我尝试这样做时,一些字符模式,如''u。。。或者HTML实体被转换为它们的等价表示,额外的空格丢失,''n,''t等也丢失,一些符号被转换为其unicode表示。

我已经编写了代码/正则表达式来满足上述情况,但我不确定是否还有更多。

编辑:我无法控制服务器。此外,一旦服务器处理了字符串,我就无法更改它,因为文本包含一些基于位置和长度的注释

示例:

从服务器接收的字符串:

"一些随机字符串,带有额外的空格,带有''t和''n,以及一些HTML实体,如>和unicode,如''u2764"

它将以HTML格式显示,如:

"一些随机字符串,带有额外的空格,带有和,以及一些HTML类似>和unicode的实体❤"

因此,如果单词HTML的注释早在位置:40,长度:4,那么现在新字符串将在位置40 处有其他内容

注意:我不能使用textContent,因为我需要突出显示基于这些注释的文本,这需要一些HTML。

小提琴示例:http://jsfiddle.net/44rct88n/

HTML:

<div ng-controller="MyCtrl">
  Hello, {{name}}!
</div>

JS:

var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
    $scope.name = "some random string, with  extra whitespaces, with 't and 'n, and some HTML entities like &gt; and unicode like 'u2764";
}

我得到的输出是:

你好,一些随机字符串,带有额外的空格,带有和,还有一些类似&#62;和类似unicode的HTML实体❤!

当您从服务器获取文本时,请使用text/plain而不是application/json,文本在RAW_TextFromServer上保持"转义",其他数据可以使用JSON.parse()进行解析

contentType : 'text/plain; charset=utf-8'
}).success(function(data, status, headers, config) {
    var theRawText = data.split(/(?:"theTextFromServer":'s*")((?:''"|[^"])*)(?:")/)[1];
    var parsedJson = JSON.parse(data);
    parsedJson["RAW_TextFromServer"] = theRawText;
    return parsedJson;
}; 
}

对于这里显示的regex,我认为json有一个键"TextFromServer",它包含您想要显示的文本
到目前为止,您已经知道javascript转义,但您需要html转义来正确表示文本。这个功能对来说很方便

function htmlEscape(str) { 
return   str.replace(/&/g, '&amp;')       // must do &amp; first
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

若要正确显示空间,可以使用具有适当样式的<pre>标记。