console.log(airline.slice(0,airline.indexOf(" ")));// TAP
寫一個判斷字串尾端有無 B 或 E 的 function,來判段機位位置 e.g. 11B 23C
1
2
3
4
5
6
7
constcheckMiddleSeat=function(seat){constposition=seat.slice(-1);if(position==="B"||position==="E")console.log("middle seat");elseconsole.log("not middle seat");};checkMiddleSeat("11B");// middle seat
checkMiddleSeat("11C");// not middle seat
toUpperCase()、toLowerCase()轉大小寫
1
2
3
4
5
6
7
8
9
10
constairline="TAP Air Portugal";console.log(airline.toLowerCase());// tap air portugal
console.log(airline.toUpperCase());// TAP AIR PORTUGAL
// 把大小寫混亂的字轉開頭大寫,後面小寫
constname="jOnAs";constnameLower=name.toLowerCase();constnameCorrect=nameLower[0].toUpperCase()+nameLower.slice(1);console.log(nameCorrect);// Jonas
constcheckBaggage=function(items){constbaggage=items.toLowerCase();// 輸入統一轉小寫,比較好處理檢查
if(baggage.includes("knife")||baggage.includes("gun")){console.log("You are NOT allowed on board");}else{console.log("Welcome aboard!");}};checkBaggage("I have a laptop, some Food and a pocket Knife");// You are NOT allowed on board
checkBaggage("Socks and camera");// Welcome aboard!
// 方法一
constcapitalizeName=function(name){constnames=name.split(" ");constnameUpper=[];for(constcharofnames){nameUpper.push(char[0].toUpperCase()+char.slice(1));}console.log(nameUpper.join(" "));};capitalizeName("jessica ann smith davis");// Jessica Ann Smith Davis
// 方法二 改用replace
constcapitalizeName=function(name){constnames=name.split(" ");constnameUpper=[];for(constcharofnames){nameUpper.push(char.replace(char[0],char[0].toUpperCase()));}console.log(nameUpper.join(" "));// Jessica Ann Smith Davis
};
constplanesInLine=function(num){console.log(`There are ${num} planes in line ${"🛩".repeat(num)}`);};planesInLine(5);// There are 5 planes in line 🛩🛩🛩🛩🛩
search()
回傳正規表達式的第一個匹配的 index,若找不到,回傳 -1。
1
2
3
4
5
6
7
8
9
10
11
constparagraph="The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";// any character that is not a word character or whitespace
constregex=/[^\w\s]/g;console.log(paragraph.search(regex));// expected output: 43
console.log(paragraph[paragraph.search(regex)]);// expected output: "."
match()
回傳一個字串匹配正規表達式的结果
使用 g 全局比對,回傳所有結果在一個陣列
沒有使用 g,回傳第一個匹配的結果,匹配的起始點,輸入字串本身,捕獲陣列或 undefined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
constparagraph="The quick brown fox jumps over the lazy dog. It barked.";constregex=/[A-Z]/g;constregexNotGlobal=/[A-Z]/;constfound=paragraph.match(regex);constfoundNotGlobal=paragraph.match(regexNotGlobal);console.log(found);// expected output: Array ["T", "I"]
console.log(foundNotGlobal);// [
// 'T',
// index: 0,
// input: 'The quick brown fox jumps over the lazy dog. It barked.',
// groups: undefined
// ]