javascript - 關(guān)于正則表達(dá)式的問(wèn)題
問(wèn)題描述
<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8' /> <title>判斷數(shù)字是否為兩位數(shù)</title> <style type='text/css'>body {font: 12px/1.5 arial;text-align: center;}.f-text {width: 50px;border: 1px solid #ccc;background: #f0f0f0;font-family: inherit;padding: 3px;margin-right: 10px;}</style><script type='text/javascript'>window.onload = function() {var aInput = document.getElementsByTagName('input');var aSpan = document.getElementsByTagName('span')[0];var i = 0;aInput[0].onkeyup = function() { this.value = this.value.replace(/[^d]/,'');} aInput[1].onclick = function() {(aInput[0].value == '') ?alert('請(qǐng)輸入數(shù)字!') :alert(/^d{2}$/.test(parseInt(aInput[0].value)) ? '√ 是兩位數(shù)' : '這是' + aInput[0].value.length + '位數(shù)');}};</script></head> <body> <input type='text' /><input type='button' value='是 否為兩位數(shù)' /> </body> </html>
1.this.value = this.value.replace(/1/,'')中的“”表示的是什么呢?
d ?問(wèn)題解答
回答1:[^d]表示不為數(shù)字的字符,其中,d表示0-9`中的任一數(shù)字,[^...]表示對(duì)字符集取反
因此,this.value.replace(/[^d]/,'')表示,若字符串的第一個(gè)字符是數(shù)字,則保留;若不是數(shù)字,則刪掉
例如,2asd、3adf的第一個(gè)字符是數(shù)字,不會(huì)被替換掉;sadf、a123的第一個(gè)字符不是數(shù)字,會(huì)被替換為空字符串'',即把該字符刪掉
回答2:''就是空的意思.replace為替換;[^d]表示非數(shù)字(^表示非,不是的意思;d表示數(shù)字)
就是當(dāng)你在輸入時(shí)(每敲一下鍵盤(pán))會(huì)觸發(fā)鍵盤(pán)事件,如果輸入的不是數(shù)字([^d]表示非數(shù)字,所以通過(guò)[^d]來(lái)判斷是不是數(shù)字)就替換(.replace為替換的意思)為空(''),所以你輸入的不是數(shù)字的話話?cǎi)R上被替換,不會(huì)顯示。
相關(guān)文章:
1. mysql - 把一個(gè)表中的數(shù)據(jù)count更新到另一個(gè)表里?2. mysql 查詢身份證號(hào)字段值有效的數(shù)據(jù)3. node.js - 為什么微信的消息MsgId出現(xiàn)重復(fù)了,無(wú)法排重了。。4. mysql的主從復(fù)制、讀寫(xiě)分離,關(guān)于從的問(wèn)題5. MySQL 截短某一列的字符串6. 請(qǐng)教使用PDO連接MSSQL數(shù)據(jù)庫(kù)插入是亂碼問(wèn)題?7. mysql - 分庫(kù)分表、分區(qū)、讀寫(xiě)分離 這些都是用在什么場(chǎng)景下 ,會(huì)帶來(lái)哪些效率或者其他方面的好處8. mysql - 字符串根據(jù)字典替換9. 視頻文件不能播放,怎么辦?10. node.js - nodejs開(kāi)發(fā)中常用的連接mysql的庫(kù)
