0%

陣列資料中的值, 如何透過replace轉換成另外一個值再塞回去陣列?

replace是在遇到字串會轉換為字串, 但是最後再塞回去變成新的值要怎麼做?

mdn 支援

1
2
3
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr); // Twas the night before Christmas...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 測式資料
let cityFilter = ['台北市', '臺北市', 950, '淡水區', '爲澎湖']

function replaceStr(cityFilter){
for (let i = 0; i < cityFilter.length; i++) {
if (cityFilter[i].includes("臺")) {
cityFilter[i].replace("臺", "台")
//return cityFilter[i].replace("臺", "台");
// 這樣就變成只會替換一個單字, 而且是最先碰到的, replace就是單純替換字
//return cityFilter
// 替換整個陣列並回傳替換的字
} else if (cityFilter[i].includes("950")) {
var numStr = cityFilter[i];
return numStr.replace("950", "台東市");
} else if (cityFilter[i].includes("淡水區")) {
var str2 = cityFilter[i]
return str2.replace("淡水區", "新北市")
} else if (cityFilter[i].includes("台南東")) {
var str3 = cityFilter[i]
return str3.replace("台南東", "台南市")
} else if(cityFilter[i].includes("偽澎湖")){
var str4 = cityFilter[i]
return str4.replace("為澎湖", "澎湖縣")
}
}
}