JavaScriptを使用してHTML文字エンティティを通常のテキストに変換します

StackOverflow https://stackoverflow.com/questions/4338963

  •  30-09-2019
  •  | 
  •  

質問

質問はそれをすべて言っています:)

例えば。我々は持っています >, 、必要です > JavaScriptのみを使用します

アップデート: :jqueryは簡単な方法のようです。しかし、軽量の解決策があるといいでしょう。これを単独で行うことができる関数のようなものです。

役に立ちましたか?

解決

あなたはこのようなことをすることができます:

String.prototype.decodeHTML = function() {
    var map = {"gt":">" /* , … */};
    return this.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);?/gi, function($0, $1) {
        if ($1[0] === "#") {
            return String.fromCharCode($1[1].toLowerCase() === "x" ? parseInt($1.substr(2), 16)  : parseInt($1.substr(1), 10));
        } else {
            return map.hasOwnProperty($1) ? map[$1] : $0;
        }
    });
};

他のヒント

function decodeEntities(s){
    var str, temp= document.createElement('p');
    temp.innerHTML= s;
    str= temp.textContent || temp.innerText;
    temp=null;
    return str;
}

alert(decodeEntities('<'))

/*  returned value: (String)
<
*/

これは、HTMLドキュメント全体をデコードするための「クラス」です。

HTMLDecoder = {
    tempElement: document.createElement('span'),
    decode: function(html) {
        var _self = this;
        html.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);/gi,
            function(str) {
                _self.tempElement.innerHTML= str;
                str = _self.tempElement.textContent || _self.tempElement.innerText;
                return str;
            }
        );
    }
}

エンティティをキャッチするためにガンボのregexpを使用したが、完全に有効なHTMLドキュメント(またはXHTML)の場合、使用できることに注意してください。 /&[^;]+;/g.

私はそこにライブラリがあることを知っていますが、ここにはブラウザ用のいくつかのソリューションがあります。これらは、HTMLエンティティデータ文字列を、Textareaや入力[Type = Text]などの文字を表示したい人間の編集可能な領域にデータ文字列を配置するときにうまく機能します。

IEの古いバージョンをサポートする必要があるため、この答えを追加し、数日分の研究とテストをまとめていると感じています。誰かがこれが便利だと思うことを願っています。

まず、JQueryを使用するよりモダンなブラウザ向けです。10(7、8、または9)のIEのバージョンをサポートする必要がある場合は、これは使用しないでください。テキストの。

if (!String.prototype.HTMLDecode) {
    String.prototype.HTMLDecode = function () {
            var str = this.toString(),
            $decoderEl = $('<textarea />');

        str = $decoderEl.html(str)
            .text()
            .replace(/<br((\/)|( \/))?>/gi, "\r\n");

        $decoderEl.remove();

        return str;
    };
}

この次のものは、上記のKennebecの作品に基づいており、主に古いIEバージョンのためにいくつかの違いがあります。これにはjQueryは必要ありませんが、それでもブラウザが必要です。

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 <br's> to save them
        str = str.replace(/((\r\n)|(\r)|(\n))/gi, " <br/>");            

        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(/<br((\/)|( \/))?>/gi, "\r\n");
    };
}

/* 
Usage: 
    var str = "&gt;";
    return str.HTMLDecode();

returned value: 
    (String) >    
*/

何も組み込まれていませんが、これを行うために書かれたライブラリがたくさんあります。

ここ 1であります。

ここ jQueryプラグインです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top