Search For Words, Replace With Links

后端 未结 4 1260
孤独总比滥情好
孤独总比滥情好 2020-12-09 07:23

I have an array like this

var words = [
    {
        word: \'Something\',
        link: \'http://www.something.com\'
    },
    {
        word: \'Something         


        
4条回答
  •  不思量自难忘°
    2020-12-09 07:54

    Given some content like:

        
    Somethsg1
    Something
    Ssething
    Something Else
    Something da
    Somethin2g

    You can use something like:

    //your array
    var words = [
        {
            word: 'Something',
            link: 'http://www.something.com'
        },
        {
            word: 'Something Else',
            link: 'http://www.something.com/else'
        }
    ];
    //iterate the array
    $.each(words,
        function() {
            //find an element with class "message" that contains "word" (from array)
            $('.message:contains("' + this.word + '")')
                 //substitute html with a nice anchor tag
                 .html('' + this.link + '');
        }
    );
    

    This solution has one immediate problem though (showed in the example too). If you search for example for Something and you find Something beautiful, the "contains" will be match.
    If you want a strict selection, you have to do:

    //for each array element
    $.each(words,
        function() {
            //store it ("this" is gonna become the dom element in the next function)
            var search = this;
            $('.message').each(
                function() {
                    //if it's exactly the same
                    if ($(this).text() === search.word) {
                        //do your magic tricks
                        $(this).html('' + search.link + '');
                    }
                }
            );
        }
    );
    

    It's your choice whether to iterate all array elements first then all the doms, or the other way around. It's also depends on which kind of "words" you are gonna search (See the two example for the "why").

    BIG WARNING: if the array contains user-defined content, you have to sanitize it before injiecting it to the elements' html!

提交回复
热议问题