仅显示字符串中的最后四位数字

时间:2015-07-31 05:37:38

标签: javascript logic

需要使用javascript从邮件中仅显示信用卡号码的最后四位数。

前:

var = "CARD SWIPED 1111222233334444
CREDIT SERVER NOT RESPONDING
CARD SWIPED
1111222233334444
CREDIT SERVER NOT RESPONDING
GIFT CARD SWIPED
1111222233334444
CREDIT SERVER NOT RESPONDING
GIFT CARD SWIPED
1111222233334444
CREDIT SERVER NOT RESPONDING
CARD SWIPED
1111222233334444"

需要预期输出为

"GIFT CARD SWIPED
4444
CREDIT SERVER NOT RESPONDING
CARD SWIPED
4444
CREDIT SERVER NOT RESPONDING
CARD SWIPED
4444
CREDIT SERVER NOT RESPONDING
CARD SWIPED
4444
CREDIT SERVER NOT RESPONDING
CARD SWIPED
4444"

对此方面的任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:2)

我对Javascript知之甚少,拥有java背景我只能想到这个逻辑。

var str = "CARD SWIPED 1111222233334444 CREDIT SERVER NOT RESPONDING CARD SWIPED 1111222233334444 CREDIT SERVER NOT RESPONDING GIFT CARD SWIPED 1111222233334444 CREDIT SERVER NOT RESPONDING GIFT CARD SWIPED 1111222233334444 CREDIT SERVER NOT RESPONDING CARD SWIPED 1111222233334444"; 
var res = str.match(/[0-9]+/g);

for (var i=0; i<res.length ; i++){
  var lastFourStr = res[i].substring(res[i].length-4, res[i].length);
  str =  str.replace(res[i], lastFourStr);
}
console.log(str);

为同一个

创建了Plnkr链接

我觉得会有比这更好的方式

  

更新:您可以将其与16位var res = str.match(/\b\d{16}\b/g);

完全匹配

模式更新

  

更新II:var regex = str.match(/\b(\d{4}( \d{4}){3})\b/g)此模式将验证带有空格的数字,我们可以将其与现有模式合并var res = str.match(/(\b\d{16}\b|\b(\d{4}( \d{4}){3})\b)/g);

答案 1 :(得分:0)

如果数字是var中的任何位置。然后这段代码可以找到值 -

         function getDigit(){

              var ex= "CARD SWIPED 1111222233334444 CREDIT SERVER 
NOT RESPONDING CARD SWIPED 1111222233334444 CREDIT SERVER NOT RESPONDING GIFT CARD SWIPED 1111222233334444 CREDIT   SERVER NOT RESPONDING GIFT CARD SWIPED 1111222233334444 CREDIT SERVER NOT RESPONDING CARD SWIPED 1111222233334444";

            var store=ex.split(" ");

                var lastFour="";

                for (var i in store) {
                    var temp=store[i];

                    var sd=parseInt(temp);
                    sd=sd+"";
                    if($.isNumeric(sd) )
                        {
                        lastFour=sd.substring((sd.length-4),sd.length);
                        }
                }                   
                alert(lastFour);}