目的
为这些字符串排序,要求去除字符串中的The
,A
以及An
的前缀后再进行排序,并把排序后的结果作为列表项展示在无序列表中。
过程
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>';
全
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sort Without Articles</title>
</head>
<body>
<style>
body {
margin: 0;
font-family: sans-serif;
background: url("https://picsum.photos/2000/2000");
background-size: cover;
display: flex;
align-items: center;
min-height: 100vh;
}
#bands {
list-style: inside square;
font-size: 20px;
background: white;
width: 500px;
margin: auto;
padding: 0;
box-shadow: 0 0 0 20px rgba(0, 0, 0, 0.05);
}
#bands li {
border-bottom: 1px solid #efefef;
padding: 20px;
}
#bands li:last-child {
border-bottom: 0;
}
a {
color: #ffc600;
text-decoration: none;
}
</style>
<ul id="bands"></ul>
<script>
// 去掉 The A An 的前缀 然后排序输出
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'];
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;
});
document.getElementById('bands').innerHTML = '<li>'+sortedbands.join('</li><li>')+'</li>';
</script>
</body>
</html>