# String Method

## Method Table

| Method                                          | return                                                                                 | example                                                                                                                                                                                                                    |
| ----------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| trim()                                          | 沒有多餘空格的 “字串” (只會移掉兩端空白)                                                                | "  s".trim();  // "s"                                                                                                                                                                                                      |
| **Capture some words**                          |                                                                                        |                                                                                                                                                                                                                            |
| indexOf(searchValue\[, fromIndex])              | <p>搜尋字串(searchValue) 所在的 “位置 (Number)”<br>第二個參數 fromIndex 可以指定從哪個位置開始搜尋，若找不到會回傳 -1</p> | 'Blue'.indexOf('blue'); //  -1                                                                                                                                                                                             |
| charAt(index)                                   | 位置(index) 所在的 “字串”，若找不到會回傳 ” 空字串                                                       | 'Brave new world'.charAt(4) // e                                                                                                                                                                                           |
| substr(start\[, length])                        | 從 start 這個位置開始，總長 length 的 “字串”．若 length 沒有值則等於等於從 start 到字串最後一個字都抓出來                  | 'abcdefghij'.substr(1, 2) // bc                                                                                                                                                                                            |
| substring(indexStart, indexEnd)                 | 從 start 這個位置開始，到不包含 end 的字串                                                            | 'abcdefghij'.substring(1, 2) // b                                                                                                                                                                                          |
| **Find something**                              |                                                                                        |                                                                                                                                                                                                                            |
| startsWith(str)                                 | 看是否為 str 開頭                                                                            | "hannah".startsWith("ha") // true                                                                                                                                                                                          |
| match(regex)                                    | 符合 regex 條件的 “Array”，若沒有丟參數進去 Array\[0] 會是 “” 空字串，若參數 regex 都不符合會回傳 null               | <p>"hannah1".match(/\d/i);</p><p>// [1, index: 6, input: 'hannah1'...]</p>                                                                                                                                                 |
| search(regex)                                   | 符合 regex 條件並第一個找到的 Number，若找不到就會回傳 -1                                                  | "hey JudE".search(/\[A-Z]/g) // 4                                                                                                                                                                                          |
| replace(regexp\|substr, newSubstr\|function)    | 原本字串用 regex 或 substr 搜尋，找到符合條件就用 newSubstr 取代成為新字串                                     | <p>var str = 'Twas the night before Xmas...';</p><p>str.replace(/xmas/i, 'Christmas');<br><br>var str = 'Twas the night'</p><p>str.replace(/the/i, (match) => "123");<br>// Twas 123 night</p>                             |
| replaceAll(regexp\|substr, newSubstr\|function) | 取代多個                                                                                   | <p>var str = "minusminusplusplus";<br>str.replaceAll('minus', "-"); // "--plusplus"</p>                                                                                                                                    |
|                                                 |                                                                                        |                                                                                                                                                                                                                            |
| slice(beginIndex\[, endIndex])                  | 切過的新字串(包含 beginIndex 不含 endIndex)                                                      |                                                                                                                                                                                                                            |
| split(\[separator\[, limit]])                   | (拆開) 回傳經過 separator 拆開的 Array，可以搭配使用 Array.join() 組合成不一樣的字串  (也可以用 regex)              | <p>"hi hana".split(" ");</p><p>// ['hi', 'hana']</p><p>split(/[^a-z]/)</p><p>// split 不是 alpha 的<br><br> <code>"/.../a/../b/c/../d/./"</code> <br><code>-> ['', '...', 'a', '..', 'b', 'c', '..', 'd', '.', '']</code></p> |
| includes(searchString\[, position])             | Boolean                                                                                | 'To be, or'.includes('To be') // true                                                                                                                                                                                      |
| charCodeAt(index)                               | 將英文字母轉為 ASCII Code                                                                     | 'Aao'.charCodeAt(1) // a 是 97                                                                                                                                                                                              |
| String.fromCharCode(Number\[, Number])          | 將數值轉換成回字串                                                                              | String.fromCharCode(65, 97, 111) // Aao                                                                                                                                                                                    |

### Match(regex)

```
// 1
"hannah1".match(/\d/i)
// 2
let regex1 = new RegExp(/\d/, "i")
"hannah1".match(regex1)
```

### [Replace multiple strings with multiple other strings](https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings)&#x20;

```javascript
var str = "minusminusplusplus"; // need convert to "--++"
let mapObj = {
    "minus": "-",
    "plus": "+"
}
str.replace(/minus|plus/gi, function(matched){
  return mapObj[matched];
});

```

### Replace(egexp|substr, newSubstr|function)

原來 replace 也是可以帶 function 的喔

**function 參數解釋**

| Possible name | Supplied value                                                                                                                                                                                                                                                                                                                                                       |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `match`       | The matched substring. (Corresponds to `$&` above.)                                                                                                                                                                                                                                                                                                                  |
| `p1, p2, ...` | The _&#x6E;_&#x74;h string found by a parenthesized capture group, provided the first argument to `replace()` was a [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) object. (Corresponds to `$1`, `$2`, etc. above.) For example, if `/(\a+)(\b+)/`, was given, `p1` is the match for `\a+`, and `p2` for `\b+`. |
| `offset`      | The offset of the matched substring within the whole string being examined. (For example, if the whole string was `'abcd'`, and the matched substring was `'bc'`, then this argument will be 1.)                                                                                                                                                                     |
| `string`      | The whole string being examined.                                                                                                                                                                                                                                                                                                                                     |

```
function replacer(match, p1, p2, p3, offset, string) {
  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
  return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString);  // abc - 12345 - #$*%
```
