Use JavaScript regex to replace numerical HTML entities with their actual characters

后端 未结 4 766
南旧
南旧 2020-12-29 16:22

I\'m trying to use JavaScript & regex to replace numerical HTML entities with their actual Unicode characters, e.g.

foo's bar
→
foo\'s bar
         


        
4条回答
  •  旧巷少年郎
    2020-12-29 16:49

    If you don't want to define all the entities you can let the browser do it for you- this bit creates an empty p element, writes the html and returns the text it produces. The p element is never added to the document.

    function translateEntities(string){
        var text, p=document.createElement('p');
        p.innerHTML=string;
        text= p.innerText || p.textContent;
        p.innerHTML='';
        return text;
    }
    var s= 'foo's bar';
    translateEntities(s);
    
    /*  returned value: (String)
    foo's bar
    */
    

提交回复
热议问题