var str = "\abc";// 字符串是獲取到的,不能更改為了\\abc var re = /^\abc/; console.log(re.test(str));//true console.log(str.match(re)); //["abc", index: 0, input: "abc"] 沒有'\' console.log(re.exec(str)); //["abc", index: 0, input: "abc"] 沒有'\' var re2 = /^\\abc/; console.log(re2.test(str));//false console.log(str.match(re2));//null console.log(re2.exec(str));//null var re3 = /^\\\abc/; console.log(re3.test(str));//false console.log(str.match(re3));//null console.log(re3.exec(str));//null var re4 = /^\\\\abc/; console.log(re4.test(str));//false console.log(str.match(re4));//null console.log(re4.exec(str));//null
擁有18年軟件開發(fā)和IT教學(xué)經(jīng)驗。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項目經(jīng)理、高級軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
反斜杠“\”是轉(zhuǎn)義字符,如果它出現(xiàn)在字符的前面,那么他們就是一個整體,比如說"n",就表示換行符。要想驗證這個我上面說的,你可以試試下面這行代碼:
var?str?=?"\abc"; console.info(str.length);?//?3
結(jié)果是3,說明'\a'是一個字符。
如果你想在字符串里面表示'\',那么你就得轉(zhuǎn)義它,給它也加一個反斜杠'\\'。
所以你上面的代碼應(yīng)該這么寫:
var?str?=?"\\abc"; var?re?=?/^\\abc/; console.log(re.test(str));//true console.log(str.match(re));//?["\abc",?index:?0,?input:?"\abc"]
比如var str="hh",會直接解析為hh。如果改成var str="\hh"的話,就是'hh'了。接下來
var?str="\\hh";/\.*/. test(str)?//true
字符串 '\\a' 是轉(zhuǎn)義操作,但是a不是有效的轉(zhuǎn)義符,所以就直接是字符a了。
'\a' === 'a' 是 true
你要這樣寫 '\\abc' 才是真正的 \abc 字符串。