正則表達式在JavaScript應用
function String.prototype.RTrim(){return this.replace(/(s*$)/g, '');}
--------------------------------------------------------------應用:計算字符串的長度(一個雙字節字符長度計2,ASCII字符計1)
String.prototype.len=function(){return this.replace([^x00-xff]/g,'aa').length;}
--------------------------------------------------------------應用:javascript中沒有像vbscript那樣的trim函數,我們就可以利用這個表達式來實現,如下:
String.prototype.trim = function(){return this.replace(/(^s*)|(s*$)/g, '');}得用正則表達式從URL地址中提取文件名的javascript程序,如下結果為page1
s='http://www.9499.net/page1.htm's=s.replace(/(.*/){0,}([^.]+).*/ig,'$2')alert(s)
##利用正則表達式限制網頁表單里的文本框輸入內容:
--------------------------------------------------------------用正則表達式限制只能輸入中文:onkeyup='value=value.replace(/[^u4E00-u9FA5]/g,’)' onbeforepaste='clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^u4E00-u9FA5]/g,’))'
--------------------------------------------------------------用正則表達式限制只能輸入全角字符: onkeyup='value=value.replace(/[^uFF00-uFFFF]/g,’)' onbeforepaste='clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^uFF00-uFFFF]/g,’))'
--------------------------------------------------------------用正則表達式限制只能輸入數字:onkeyup='value=value.replace(/[^d]/g,’) 'onbeforepaste='clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^d]/g,’))'
--------------------------------------------------------------用正則表達式限制只能輸入數字和英文:onkeyup='value=value.replace(/[W]/g,’) 'onbeforepaste='clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^d]/g,’))'
相關文章:
