开发者

JavaScript htmlentities French

开发者 https://www.devze.com 2023-02-08 19:09 出处:网络
I have a .NET MVC page with a list of items that each have <%: %> encoded descriptions in the rel.

I have a .NET MVC page with a list of items that each have <%: %> encoded descriptions in the rel. I want to be able to search for all items with a rel that contains my search query.

One of the fields has a value with htmlentities rel='D&eacute;coration'

I type "Décoration" in the search box, let jQuery search for all elements that have a 'rel' attribute that contains (indexOf != -1) that value:

no results!

Why? because Décoration != D&eacute;coration.

What would be the best solution to compare these two? (Has to work for all special ac开发者_如何学JAVAcented characters, not just &eacute;)

P.S. (I tried escape/unescape on both sides, also tried the trick to append it to a div and then read it as text, this replaces dangerous stuff, but doesn't replace é (it doesn't have to because it's valid in utf-8 anyway))


Since the &eacute; and like are html entities, you can set the html content of a temporary div with the garbled string, and retrive the decoded string using the text content of the element. The browser will do the decoding work for you.

Using jQuery :

function searchInRel(needle) {
    return $('[rel]').filter(function(i,e) {
        var decodedText = $('<div/>').html(e.attr('rel')).text();
        return (decodedText.indexOf(needle) != -1);
    };
}

Using just the DOM :

function decodeEntities(text) {
    var tempDiv = document.getElementById('tempDiv');
    tempDiv.innerHTML = text;
    return tempDiv.textContent;
}


If you serve your pages with UTF-8 encoding, you won't need to use entities for all the accented characters. Problem solved.


You can decode the html entities. Just copy the two javascript methods from HERE

var decoded = 'Décoration';
var entity = html_entity_decode('D&eacute;coration');
console.log(decoded == entity);
0

精彩评论

暂无评论...
验证码 换一张
取 消