从Value输入中添加String的特定部分

时间:2016-10-28 16:58:52

标签: javascript substring

我现在正在编写一段代码,我需要在字符串中添加前3个字符,然后将它们与最后2个字符进行比较,以确保它们匹配。

  

例如:ID 12306有效,因为1 + 2 + 3 = 6,0 + 6 = 6.

我之前在这里找到了一个关于类似问题的话题(早在2012年),但是代码示例使用了2个静态数字变量,当我尝试使用我的HTML输入值实现相同的方法时,它似乎做了什么都没有。

var custId = document.getElementById("custid").value;

function validateId(custid) {
  var custId2 = custId;
  var custId3 = custId;

  custId2 = custId2.substring(0, 2);
  custId3 = custId3.substring(3, 5);

  custid = custid.split('');
  var sum = 0;

  for (var i = 0; i < custid.length; i++) {
    sum += parseInt(custid[i], 10);
  }

  return sum;

  if (add(custId2) != add(custId3)) {
    output = "ID error. The first three digits must sum to the value ' +
             'of digits 4 and 5. e.g. 12306 is a valid value";
    output = custId2 + "<br />" + custId3;
    addToOutput();
    return false;
  }
}

2 个答案:

答案 0 :(得分:1)

虽然你的方法有许多问题,如评论中所述(错误的套管,多次返回,子串索引),但我提供了一个你可以根据自己的喜好使用的解决方案。

var validateId = function(custId) {
  var custId2 = custId.substring(0, 3).split('');
  var custId3 = custId.substring(3,5).split('');

  var sum2 = 0; 
  var sum3 = 0; 

  custId2.forEach((e) => {
    sum2 += parseInt(e);
  })

  custId3.forEach((e) => {
    sum3 += parseInt(e);
  })

  if(sum2 !== sum3) {
    console.log("ID error. The first three digits must sum to the value of digits 4 and 5. e.g. 12306 is a valid value")
  } else {
    console.log("Success");
  }
}

validateId("12306"); 

示例 - http://plnkr.co/edit/vtrU8Hs4Bv6FJS1qFnKn?p=preview

答案 1 :(得分:0)

所以我设法使用以下代码:

function processData(){
    var custId = document.getElementById("custid").value;
    var custName = document.getElementById("custname").value;
    var ticketType = document.getElementById("tickettype").value;
    var ticketQty = document.getElementById("qty").value;
    var delType = document.getElementById("delivtype").value;
    validateId(custId);

function validateId(custId){
    if(!custId){
        output = "Customer ID cannot be blank";
        addToOutput();
        return false;}

    if(custId.length != 5){
        output = "Customer ID must be 5 digits in length";
        addToOutput();
        return false;}

    if(isNaN(custId)){
        output = "Customer ID must be numeric";
        addToOutput();
        return false;}

    var custId2 = custId;
    var custId3 = custId;

    custId2 = custId.substring(0,3);
    custId3 = custId.substring(3,5);

    custId = custId.split('');
    var sum = 0;
    var sum2 = 0;

    for (var i = 0; i < custId2.length; i++){
        sum += parseInt(custId2[i],10);
    }

    for (var i2 = 0; i2 < custId3.length; i2++){
        sum2 += parseInt(custId3[i2],10);
    }

    if(sum !== sum2){
        output = "ID error. The first three digits must sum to the value of digits 4 and 5. e.g. 12306 is a valid value";
        addToOutput();
        return false;}

    output = "Customer ID Valid!"
    addToOutput();
    return true;
}