iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 6
0
自我挑戰組

What a good thing we lose? What a bad thing we knew?系列 第 6

【Day 6】 使用JavaScript 做字串處理

大家好,今天跟大家一起學習如何使用JavaScript語法 來處理字串。

首先在JavaScript中有個內建功能為 串接字串。
如果你把 + 運算子用於數字上,他們會相加。 但是如果把 + 用在字串上,會把第一個字串 加上 第二個字串。

msg = "Hello," + ",ithome"
console.log(msg);

-> Hello,ithome

https://ithelp.ithome.com.tw/upload/images/20181020/20112000RYYalnDuN2.png

var i = 10;
var j = 15;
var sum = i + j ;
console.log(sum);

->25

https://ithelp.ithome.com.tw/upload/images/20181020/201120006TOhQwmNEO.png

var s = "Hello, ithome"
s.length //s 字串長度

https://ithelp.ithome.com.tw/upload/images/20181020/20112000wm78ICoHXN.png

s.charAt(0); //s 第一個字元

https://ithelp.ithome.com.tw/upload/images/20181020/20112000q52Z5rmuWy.png

s.charAt(s.length-1) //最後一個字元

https://ithelp.ithome.com.tw/upload/images/20181020/20112000DZ14zUiIzV.png

s.substring(0,5) //從索引0,取5個字元  -> Hello

https://ithelp.ithome.com.tw/upload/images/20181020/20112000mqBtgKeEEV.png

s.slice(-6) //取倒數6個字元

https://ithelp.ithome.com.tw/upload/images/20181020/20112000Dj42n4LpLE.png

s.indexOf("H") // 取H字母 在字符串中首次出現的位置

https://ithelp.ithome.com.tw/upload/images/20181020/20112000zkMasCviPH.png

s.replace("o","O") //用"O" 取代"o" ->這邊發現無法完全取代o, 因此要加上正規表達式,改成

https://ithelp.ithome.com.tw/upload/images/20181020/201120006vAmbZQ45N.png

s.replace(/o/g,"O")

https://ithelp.ithome.com.tw/upload/images/20181020/20112000ASLkiymwwG.png

註:這是因為 JavaScript replace 的第一個參數其實是 Regex 而非字串,如果你輸入字串,就只會取代第一個遇到的字串,導致和預期不同的問題。要解決 JavaScript String.replace 不會取代全部字串的問題很簡單,只要用正規表達去寫即可。(參考至碼人日誌-JavaScript String Replace All)

s.toUpperCase() //全部字串轉大寫    

https://ithelp.ithome.com.tw/upload/images/20181020/20112000sOQeh6wcRn.png

s.toLowerCase() //全部字串轉小寫

https://ithelp.ithome.com.tw/upload/images/20181020/20112000BRh81ORYkA.png

參考資料:
JavaScript大全
https://www.books.com.tw/products/0010542183
碼人日誌-JavaScript String Replace All
https://coder.tw/?p=7258


上一篇
【Day 5】 在Visual Studio 2017 使用gmail發信
下一篇
【Day 7】 隱藏在黑暗之中的網路-暗網
系列文
What a good thing we lose? What a bad thing we knew?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言