尋找比對字串:match、search === match、search --- 用於尋找另一字串是否有該字串的語法,無法用於陣列,且都可用於正則表達式。 另有其他尋找字串的方式,比如 includes、indexOf 但這些可用於陣列,且無法使用正則表達式。詳細見:[尋找是否包含某元素:includes、indexOf](https://hackmd.io/_syPyPdDRvejw3QTiHjaNQ?view)。 [match](https://codepen.io/betty-hu/pen/bGQXgdb?editors=0010) --- > str . match ( regexp ) ```jsx /* 沒有使用正規表達式,僅使用字串搜尋 */ 'some text'.match('Some') // null /* 使用正規表達式 */ 'some text'.match(/some/i) // ['some', index: 0, input: 'some text', groups: undefined] ``` 尋找字串是否在另一字串中,沒找到回傳 null。 若是找到,返回陣列,第一個元素是完整匹配內容,接著是匹配的群組 (capturing group)。 [search](https://codepen.io/betty-hu/pen/YzRmpee?editors=0012) --- > str . search ( regexp ) ```jsx /* 沒有使用正規表達式,僅使用字串搜尋 */ 'some text'.search('text') // 0 'some text'.search('TEXT') // -1 /* 使用正規表達式 */ 'some text'.search(/TEXT/i) // 0 ``` 找出字串在另一字串中的位置,有找到回傳字串的起始位置,沒找到回傳 -1。 跟 `indexOf()` 相同都是尋找並回傳位置,只是 `search()` 可以用正規表示式當參數,且只能作用在字串上,不能用於陣列。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up