iT邦幫忙

2024 iThome 鐵人賽

DAY 18
0

Sort Without Articles

將樂團的名字去做英文字母a-z的順序排列,但是會把樂團前面開頭有the,an,a的字眼排除掉,再去排序.

https://ithelp.ithome.com.tw/upload/images/20240927/20169174xZOlRlGLXn.png

個人codepen

技巧點

1. sort()

  • 對陣列的所有元素去做排序,並回傳此陣列。預設排序的方式是按照字串的 Unicode 編碼位置。
  • 詳細原理,在之前第五天有介紹過,可參考這
// 排列數字
const nums = [9,2,4,3,1,7];
nums.sort(); // [1, 2, 3, 4, 7, 9]

// 排列數字,但數字的位數都不太一樣時,按預設方式排列會出現非預期狀況
const nums = [90,2,777,32,1,117];
nums.sort(); // [1, 117, 2, 32, 777, 90]

// 為確保數字排列方式,是預期的由小到大,就應該在sort()中放入比較函式
const nums = [90,2,777,32,1,117];
nums.sort((a, b) => a - b); // [1, 2, 32, 90, 117, 777]

// 英文的排列,按照預設方式Unicode 編碼位置排列
const abc = ['z','a','k','c'];
abc.sort(); // ['a', 'c', 'k', 'z']

2. replace(pattern, replacement)

  • 將匹配到的字眼,替換掉,返回一個新字串。pattern為你想要匹配的字串,可以放入正則表達;replacement為要替換的字串或是一個函式。
// pattern放入字串去匹配對應的
const today = 'today is sunny';
const update = today.replace("sunny", "foggy");
console.log(update); // today is foggy

// 如果pattern沒有匹配到,那就不會更動任何字
const today = 'today is sunny';
const update = today.replace("rainy", "foggy");
console.log(update); // today is sunny
  • 基本上replace只會替換一次,所以如果有多個重複的字串要替換掉,要使用replaceAll()
// 第一個匹配的字串會被替換掉,剩下的不理
const today = 'today is sunny, i love sunny';
const update = today.replace("sunny", "foggy");
console.log(update); // today is foggy, i love sunny

// 要使用replaceAll,所有匹配的都要換掉
const today = 'today is sunny, i love sunny';
const update = today.replaceAll("sunny", "foggy");
console.log(update); // today is foggy, i love foggy
  • 當pattern為一個空字串時,沒有找到匹配的對象,就會直接在最前面插入你要新增的文字
const linkinPark = "good";
const txt = linkinPark.replace("", "so ");
console.log(txt); // so good
  • pattern可以使用正則表達去匹配
const description = 'Jack is a bad guy';
const txt = description.replace(/^[a-z]+\s/i, "Mary "); i為不區分大小寫
console.log(txt); // Mary is a bad guy

心得

有上次的sort練習,這次就比較快速,但replace的用法,還可以用fn去當replacement

function f2c(x) {
  function convert(str, p1, offset, s) {
    return `${((p1 - 32) * 5) / 9}C`;
  }
  const s = String(x);
  const test = /(-?\d+(?:\.\d*)?)F\b/g;
  return s.replace(test, convert);
}

找到替換的字串後,進一步將華氏轉成攝氏溫度,非常酷,但我還不熟...


上一篇
CSS Text Shadow Mouse Move Effect 滑鼠操作文字陰影
系列文
鱷魚帶我練習JavaScript之個人練功坊18
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言