今天在一本書《Javascript for impatient programmers》上看到寫的是這樣用javascript
match(regExp: string | RegExp): RegExpMatchArray | null
複製代碼
上面用的是類Typescript的寫法來講明,我的以爲挺好的 意思是match方法接受傳遞一個參數regExp
,這個regExp
能夠字符串或者正則表達式。返回的正則匹配後的結果的數組,若是什麼也沒匹配到的話,返回的就是null
。 而且有以下說明html
If
regExp
is a regular expression with flag/g
not set, then.match()
returns the first match forregExp
within the receiver. Ornull
if there is no match. IfregExp
is a string, it is used to create a regular expression before performing the previous steps.java
裏面提到若是傳遞的參數regExp
是一個字符串的話,match
方法會先把它變成正則表達式(即new RegExp(regExp)
)而後在按照證實表達式進行匹配,此時至關於執行的是recevier.match(new RegExp(regExp))
了。 爲了進一步確認,我去查看了MDN,看到是這麼說的正則表達式
語法:
str.match(regexp)
參數:regexp
A regular expression object. If a non-RegExp objectobj
is passed, it is implicitly converted to aRegExp
by usingnew RegExp(obj)
. If you don't give any parameter and use the match() method directly, you will get anArray
with an empty string:[""]. 針對上面說的若是傳字符會先轉爲正則表達式後再匹配的說法是一致的。express
我本身寫了寫代碼測試下 數組
咱們能夠看到傳遞字符串.v
和傳遞/.v/
是同樣的,果真是轉化爲正則表達式後再執行的 我又接着測試了點別的 測試
null
了,不是應該也變成
/\w{2}v/
再進行匹配的嗎 我接着用
'love'.match('\\w{2}v')
試了下 好了,完美~
原來是一個\
會被轉義,只是一個\
是不行的,兩個\
就搞定了。 在此,String.prototype.match就講完了。 在實際使用的過程當中咱們應該按照傳遞正則表達式來使用,爲何?否則像上面的傳遞個字符串.v
,你本身還覺得是匹配一個小數點.
和一個v
呢,實際結果是一個除換行符之外的任意字符
和一個v
,和你原來預想不同。 咱們平時還有幾個方法樣式能夠傳遞字符串或者正則表達式,好比replace
等,你們自行試試吧。 碼字手疼,Over。ui
更多內容能夠查看個人博客spa