Here's a pretty simple solution. If you manually compare strings, it is recommended to use localeCompare , which will be correctly sorted, even if the language corresponding to the user's language dictates a different sort order. But this function alone will not solve our problem. Based on @wZVanG's clever answer, we will replace any character without words using the \W regex character group at the beginning of the line with the letter z , which automatically sorts them to the end of the list.
Please note that one of the drawbacks is that if any of your words starts with more than one z , they will be sorted after special characters. A simple workaround is to add more than z to the string, as in return a.replace(/^\W+/, 'zzz').localeCompare(b.replace(/^\W+/, 'zzz') .
var array = ["Banana", "Apple", "*Canana", "Blackberry", "Banana", "*Banana", "*Apple"]; array.sort(function(a,b) { return a.replace(/^\W+/, 'z').localeCompare(b.replace(/^\W+/, 'z')); });
source share