
JS 字串 – 在本文中,我將向你展示在Javascript程式設計中, js string 字串普遍都會使用的5大類10方法, 當中的功能為在字串上進行:
- javascript 尋找 (js contains, js startsWith, js endsWith, js matches)
- javascript 擷取 (js substring)
- javascript 對比 (js equals)
- javascript 組合 (js concat, js join)
- javascript 分割 (js split, js trim)
方法 | 例子: |
搜查的關键字是否存在於字串中: String.contains(String); String.contains(“要搜查的關键句”); | var str = “I believe I can fly”; console.log(str.includes(“believe”)); //true |
搜查的關键字是否存在於字串的開端: String.startsWith(String); String.startsWith(“要搜查的關键句”); | var str = “I believe I can fly”; console.log(str.startsWith(“I”)); //true console.log(str.startsWith(“believe”)); //false console.log(str.startsWith(“fly”)); //false |
搜查的關键字是否存在於字串的尾端: String.endsWith(String); String.endsWith(“要搜查的關键句”); | var str = “I believe I can fly”; console.log(str.endsWith(“I”)); //false console.log(str.endsWith(“believe”)); //false console.log(str.endsWith(“fly”)); //true |
字串中是否具有一定的Pattern: String.match(RegxPattern); String.match(“Regex Pattern”); | var str1 = “I believe I can fly”; var str2 = “www.jprogramstudy.com”; console.log(str1.match(“www(.*)”)); // null console.log(str2.match(“www(.*)”)); /* [ ‘www.jprogramstudy.com’, ‘.jprogramstudy.com’, index: 0, input: ‘www.jprogramstudy.com’, groups: undefined ] */ |
撷取字串: String.substring(Int32, Int32); String.substring(由第幾個字元開始撷取, 要撷取多少個); | var str = “I believe I can fly”; console.log(str.substring(4, 15)); //lieve I can |
分割字串: String.split(String); String.split(“要分割的字串”); | var str = “I believe I can fly”; console.log(str.split(“I”)); //[ ”, ‘ believe ‘, ‘ can fly’ ] |
移除字串兩邊的空白: String.trim(); String.trim() | var str = ” I believe I can fly “; console.log(str.trim()); //I believe I can fly |
字串對比 (完全與要對比的字串一樣): String == “要對比的字串” | var str1 = “I believe I can fly”; var str2 = “i believe i can fly”; var str3 = “I believe I can fly”; console.log(str1 == str2); //false console.log(str1 == str3); //true |
字串組合: String.concat(String); String.concat(“組合對象字串”); | var str1 = “I believe I can fly! “; var str2 = “Hello World!”; console.log(str1.concat(str2)); //I believe I can fly! Hello World! |
字串數組組合: String[].join(String); String[].join(“接合字串”); | let strs = [“I”, “believe”, “I”, “can”, “fly.”]; console.log(strs.join(” “)); //I believe I can fly |
相關頁面: JS 字串 – String功能速查表(二) – 尋找, 換成大小寫, 字串重覆
參考資料: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String