Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the strings inside the plugin

I have a javascript plugin here that I wrote for a website and I am working on modifying the plugin to add some additional functionality.

The plugin earlier accepted an array of items as the input as follows (to finally create a small visualization):

Tom Hank
Will Smith
Chirstopher Nolan
Keanu Reeves

Internally, the plugin used a sort function to sort the names as follows:

groups = groups.sort(function (a, b) {
            if (a.content > b.content) {
                return 1;
            }
            if (a.content < b.content) {
                return -1;
            }
            return 0;
        });

where a.content and b.content are all strings such as "Keanu Reaves" etc.

However, now I have changed the input being sent to the plugin and instead of sending the input strings, I now send html as input. For eg:

<div class="sampleDiv"><span class="">Keanu Reaves</span></div>
<div class="sampleDiv"><span class="">Christopher</span></div> etc.

where each item is formed by

var itemSrc= '<div class="sampleDiv"><span class="">' +
              'Keanu Reaves' + 
             '</span></div>';

I have to sort the items in the plugin similarly (in that sort function), but now that I am sending html (a.content now has the above html), I wanted to get some ideas from SO on how I could sort in the above function (Previous sort should also be retained, in case I later change the input to sending only strings). Any suggestions?

like image 409
user1240679 Avatar asked Jun 15 '26 00:06

user1240679


1 Answers

In your sort function, first strip the html tags. With the resulting string, then perform the sort.

    groups = groups.sort(function (a, b) {
        var x = a.toLowerCase().replace(/<[a-zA-Z\/][^>]*>/g,''), y = b.toLowerCase().replace(/<[a-zA-Z\/][^>]*>/g,'');
        return x < y ? -1 : x > y ? 1 : 0;
    });

I hope this helps.

like image 75
gaurav.singharoy Avatar answered Jun 17 '26 15:06

gaurav.singharoy