[JS30] Day17: Sorting Band Names without articles
這一天的目標是要將清單上的樂團名字,依照字母的順序排進去,但是要將the
、a
、an
的無用字眼先給去除。
HTML
<ul id="bands"></ul>
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",
];
function strip(string) {
return string.replace(/^(a |an |the)/i, "").trim(); // 去除regex字串,並透過trim清除空白
}
const sortedBands = bands.sort((a, b) => (strip(a) > strip(b) ? 1 : -1));
const list = document.querySelector("#bands");
list.innerHTML = sortedBands.map((bands) => `<li>${bands}</li>`).join(""); // 將array改變成字串加入到innerHTML時,會多出逗號(,),因此要先透過`.join`結合