实现效果:
为一组字符串数组,去除前缀进行排序。
关键点:
1.声明去前缀函数,使用String.replace()函数实现,第一参数使用字面量正则表达式。
function delPrefix(item){
return item.replace(/^(The|A|An)\s{1}/,'');
}
2.使用Array.sort()对数组进行排序,将数组中逐项使用delPrefix()去掉前缀后再进行对比。
var sortedbands = bands.sort(function(a,b){
return delPrefix(a) > delPrefix(b) ? 1 : -1;
});
3.使用选择器选中无序列表#bands,将排序后的数组作为列表项插入其中。
document.getElementById('bands').innerHTML = '<li>'+arr.join('</li><li>')+'</li>';
javascript
const bands = ['The Plot in You', 'The Devil Wears Prada', 'Pierce the Veil', 'Norma Jean', 'The Bled', 'Say Anything', 'The Midway State', 'We Came as Romans', 'Counterparts', 'Oh, Sleeper', 'A Skylit Drive', 'Anywhere But Here', 'An Old Dog'];
var ul = document.querySelector("#bands");
function delPrefix(item){
return item.replace(/^(The|A|An)\s{1}/,'');
}
var sortedbands = bands.sort(function(a,b){
return delPrefix(a) > delPrefix(b) ? 1 : -1;
})
console.log(sortedbands);
for(var i = 0; i < bands.length; i++){
ul.innerHTML += `
<li>
${bands[i]}
</li>
`;
}