正则表达式的各种用法

表单验证只能输入数字和点,否则就输入不进去,用的事件是keyup

obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
obj.value = obj.value.replace(/\d{14,}/g, obj.value.slice(0,14));

 输入银行卡号自动四位加空格

<input type="tel" v-model="mobile" placeholder="输入" maxlength="19">
 
watch:{
  mobile(newValue,oldValue){
    this.mobile  =  newValue.length  >  oldValue.length  ?  newValue.replace(/\s/g,'').replace(/\D/g,'').replace(/(\d{4})(\d{0,4})(\d{0,4})(\d{0,4})/g,  '$1 $2 $3 $4')  :  this.mobile.trim()
  }
}

给数字加千分符

<script language="JavaScript" type="text/javascript">
function formatNumber(num){
if(!/^(\+|-)?(\d+)(\.\d+)?$/.test(num)){
return num;
}
var a = RegExp.$1,b = RegExp.$2,c = RegExp.$3;
var re = new RegExp("(\\d)(\\d{3})(,|$)");
while(re.test(b)){
b = b.replace(re,"$1,$2$3");
}
return a +""+ b +""+ c;
}
var num=3243245134151343.18787;
console.log(formatNumber(num))
/*alert("num="+num+",四舍五入:"+Math.round(num)+",两位有效数字:"+num.toFixed(2)+",添加千位分隔符:"+formatNumber(num)); */
</script>

 

 

/* 金额转千分位格式 */
function formatMoney(num) {
if(num || num == '0'){
num = parseFloat(num, 10);
return (num.toFixed(2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}else{
return '';
}
}
修改后的如下:
formatMoney(num) {
num = num.replace(/[^\d+$]/ig,'')
if(num || num == '0'){
num = parseFloat(num,10);
return (num + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}else{
return '';
}
}

允许输入负1的加入千分位
formatMoney(num) {
// 当status值为3时允许输入-1,其它负数不允许
if( /^-1$/.test(num) ) {
return num;
} else if( /^-1\d+$/.test(num) ) {
return '-1'
} else if( !/^-$/.test(num) ) {
num = num.replace(/[^\d+$]/ig,'')
if(num || num == '0'){
num = parseFloat(num, 10);
return (num + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}else{
return '';
}
} else {
return num
}
 
}


  function toThousands(num) {
            var result = '';
            num = Number(num.toString() || 0).toFixed(2);
            var numAry = num.toString().split(".");
            var preNum = numAry[0];
            var lastNum = numAry[1];
  


            while (preNum.length > 3) {
                result = ',' + preNum.slice(-3) + result;
                preNum = preNum.slice(0, preNum.length - 3);
            }
            if (preNum) {
                result = preNum + result;
            }
            result=result+"."+lastNum;


            return result;
        }

 

// 如下是支持边输入边加千分位并且保留两位小数

formatMoney(num) {
num = num.replace(/[^\d+|\.\d*$]/ig,'')
if(num || num == '0'){
if(/\.+/ig.test(num) && num.split('.')[1].length>2){
num = Number(num.split(',').join('')).toFixed(2);
}
return (num+'').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}else{
return '';
}
}

 

修改如下:

function toThousands(num) {

    num = num.replace(/[^\d+|.?$]/ig,'');
            var result = '';
            num = Number(num.toString() || 0).toFixed(2);
            var numAry = num.toString().split(".");
            var preNum = numAry[0];
            var lastNum = numAry[1];
  


            while (preNum.length > 3) {
                result = ',' + preNum.slice(-3) + result;console.log(result);
                preNum = preNum.slice(0, preNum.length - 3);console.log(preNum);
            };
            if (preNum) {
                result = preNum + result;
            }
            result=result+"."+lastNum;


            return result;
        }


/* 千分位转非千分位金额 */
function formatNumber (money) {
var newNumber;
newNumber = money && money.split(',').join('');
return newNumber;
}


获取href里面带的某一个参数

uri =' http://community.antfortune.net/community/comment.htm?commentId=2016090102900100017010&topicId=2088102147230111'
var value = uri.match(new RegExp('[\?\&]' + param + '=([^\&]*)(\&?)', 'i')); //param是找的关键字例如commentId

(value里输出来的值如右侧  ["?commentId=2016090102900100017010&", "2016090102900100017010", "&"] )

return value ? decodeURIComponent(value[1]) : value;

匹配图片var regImg=/(<img\b[^>]*src\s*=\s*"[^>"]*\.(?:png|jpg|bmp|gif)"[^>]*>)/;

后端返回的可能是U_1或S_2等等
var reg = /(\{\{([a-z]_[0-9]+)\}\})+/gi;
var str1 = $content.replace(reg, function (r, $1, $2) {
if (/^U/.test($2)) {
var uIndex = $2.substr($2.length - 1);

var ATUSRs = (uIndex==2)? $referenceMap.ATUSR[0].atUserId: $referenceMap.ATUSR[uIndex].atUserId;
if(ATUSRs && uIndex!=2){
return '<span class="friends" userid='+$referenceMap.ATUSR[uIndex].atUserId+'>'+$referenceMap.ATUSR[uIndex].referString+'</span>';
}else if(uIndex==2 && ATUSRs){
return '<span class="friends" userid='+$referenceMap.ATUSR[0].atUserId+'>'+$referenceMap.ATUSR[0].referString+'</span>';
}else{
return '<span class="friends" userid="">'+$referenceMap.ATUSR[uIndex].referString+'</span>';
}
};
if (/^S/.test($2)) {
var uIndex = $2.substr($2.length - 1);
return '<span class="atFriend">'+$referenceMap.STOCK[uIndex].referString+'</span>';
};


exec方法 (获取浏览器里的cookie里的某一个key及value值)

var m = new RegExp('\\b' + key + '\\=([^;]+)').exec(document.cookie);
var str = "session.cookieNameId=ALIPAYJSESSIONID; ctoken=W7QjPHxCLOeEv1E5; ALIPAYJSESSIONID=GZ005V4hQPczTAWj8zqPq7SyST3mLyauthcenterGZ00";
//str里存的是电脑网页里的cookie的值,想获取cookie里的ctoken的值

/\bctoken\=([^;]+)/g.exec(str)    得出结果  ["ctoken=W7QjPHxCLOeEv1E5", "W7QjPHxCLOeEv1E5"] 

注:把上面这行正则改成用new regexp的形式去写就是第一行的那种写法,key是变量,这里就是指ctoken,  str里就是document.cookie里的值

 

//

身份证号码的*替换

str = Regex.Replace(str, "(\\d{4})(\\d+)(\\d{4})", "$1***********$3");




String.prototype.escapeHTML = function () {
return this.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;');
}; //将后台返回来的标签元素转变成让标签显示在浏览器上

用正则匹配返回日期
new BaseJs().dateFormat(v, "{y}{mm}{d} {h}:{m}")
dateFormat: function (time, tpl) {
var zeroFix = function (d) {
if (d < 10)
return "0" + d;
return d;
};

var date = new Date(time),
year = date.getFullYear(),
years = date.getFullYear(),
month = zeroFix(date.getMonth() + 1)
months = zeroFix(date.getMonth() + 1),
day = zeroFix(date.getDate()),
days = zeroFix(date.getDate()),
hour = zeroFix(date.getHours()),
minute = zeroFix(date.getMinutes()),
second = zeroFix(date.getSeconds());
var nowDate = new Date(),
nowYear = zeroFix(nowDate.getFullYear()),
nowMonth = zeroFix(nowDate.getMonth() + 1),
nowDay = zeroFix(nowDate.getDate());

return tpl.replace(/\{([^{}]+)\}/g, function (a, b) {
switch (b) {
case "y":
year = (years == nowYear)? "": years+"-";
return year;
case "mm":
if(years == nowYear && months == nowMonth && days == nowDay){
month = "今天";
}else if (years == nowYear && months == nowMonth && days == nowDay-1){
month = "昨天";
}else{
month = month+"-";
};
return month;
case "d":
if(years == nowYear && months == nowMonth && days == nowDay || years == nowYear && months == nowMonth && days == nowDay-1){
day = "";
}
return day;
case "h":
return hour;
case "m":
return minute;
case "s":
return second;
}
});
},
posted @ 2016-08-30 17:30  小小公举  阅读(1489)  评论(0编辑  收藏  举报