> 本文介紹一些常用的字符串相關的屬性和方法
[TOC]
## 字符串屬性
| 屬性 | 描述 |
| --- | --- |
| length | 返回字符串的長度 |
### length 屬性
> 返回字符串的長度
~~~
var myname = "wangking";
console.log(myname.length)
~~~
## 字符串方法
更多方法實例可以參見:[JavaScript String 對象](https://www.runoob.com/jsref/jsref-obj-string.html)。
| 方法 | 描述 |
| --- | --- |
| indexOf() | 返回字符串中檢索指定字符第一次出現的位置 |
| lastIndexOf() | 返回字符串中檢索指定字符最后一次出現的位置 |
| match() | 正則匹配,返回數組多值 |
| replace() | 替換與正則表達式匹配的子串 |
| split() | 把字符串分割為子字符串數組 |
| substr() | 從起始索引號提取字符串中指定數目的字符 |
| toLowerCase() | 把字符串轉換為小寫 |
| toUpperCase() | 把字符串轉換為大寫 |
| trim() | 移除字符串首尾空白 |
### substr(start,[length]) 方法
> 例:從字符串中取得 13:50的數據
~~~
let str = "now is 13:50";
console.log(str.substr(str.indexOf('is ')+3))
~~~
### indexOf(searchVal) 方法
> 例:從字符串中取得 13:50的數據
~~~
let str = "now is 13:50";
console.log(str.substr(str.indexOf('is ')+3))
~~~
### lastIndexOf(searchVal) 方法
> 例:從字符串中提取出后綴名
~~~
let str = "xxx.yy.gif";
console.log(str.substr(str.lastIndexOf('.')))
~~~
### match(regexp) 方法
> 正則匹配,返回數組多值
~~~
var str="1 plus 2 equal 3"
console.log(str.match(/\d+/g)) // 返回數組 [1,2,3]
~~~
### replace(searchValue, newValue) 方法
> 字符串替換,支持正則
~~~
let str = "Hello Microsoft Microsoft!";
console.log(str.replace('Microsoft', 'wk')) //只會替換1次Microsoft
console.log(str.replace(/MiCrosoft/ig, 'wk')) // 全局替換,使用正則方式
~~~
### split(separator) 方法
> 將字符串分割為數組
~~~
var txt = "a,b,c,d,e";
console.log(txt.split(','))
~~~
### toLowerCase() 方法
> 例:將字符串轉化為小寫
~~~
var text = "Hello World!";
console.log(text.toLowerCase())
~~~
### toUpperCase() 方法
> 例:將字符串轉化為大寫
~~~
var text = "Hello World!";
console.log(text.toUpperCase())
~~~
### trim() 方法
~~~
var str = " Hello World! ";
console.log(str.trim())
~~~