ultraloveninja
ultraloveninja

Reputation: 2139

Sort text in a div alphabetically with jQuery

Is it possible to find some particular text in a div and then sort it alphabetically?

For example, in this block of text in a div:

<div class="text-block">
Jim, Mike, Ali, and Marsha went to the store.
</div>

I'd want to have Jim, Mike, Ali, and Marsha be ordered alphabetically so the output would be this instead:

<div class="text-block">
Ali, Jim, Marsha, and Mike went to the store.
</div>

I feel that's pretty much impossible outright, but maybe just a find and replace instead? Not too sure on what the best method would be.

Upvotes: 0

Views: 777

Answers (3)

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

You can do this: Use regex to get the names starting from capital letter. Remaining text needs to be concatenated after sorting names. See below:

var str = $('.text-block').text();//Read the div

var names = str.match(/\b[A-Z].*?\b/g);//Find out names

var lastName = names[names.length - 1];
var lastNameIndex = str.indexOf(lastName);
var remainingStr = str.slice(lastNameIndex + lastName.length);//remaining 
                                                              //text
names = names.sort();
names[names.length - 1] = " and " + names[names.length - 1];
var newStr = names + remainingStr;
$('.text-block').text(newStr);//update div
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-block">
  Jim, Mike, Ali, and Marsha went to the store.
</div>

Upvotes: 0

Neil
Neil

Reputation: 14313

You can accomplish this with regex. This way you can support more versatile input.

$(".text-block").html(function(idx, oldhtml) {
    return oldhtml.replace(/[, a-z]+and [a-z]+/gi,function(a) {
        tmp = a.replace(" and "," ").split(/[^\w]+/).sort();
        return tmp.slice(0,-1).join(", ") + ", and " + tmp.pop();
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-block">
Jim, Mike, Ali, and Marsha went to the store.
</div>

Upvotes: 1

Daniel Taub
Daniel Taub

Reputation: 5369

Like that :

divText = $('.text-block').text();
arr = divText.split(",");
lastStr = arr.pop(-1);
arr.sort();
arr.push(lastStr);
$('.text-block').text(arr.toString());

Upvotes: 0

Related Questions