JavaScript中字符串的增量数字部分

时间:2018-06-30 10:44:17

标签: javascript jquery vue.js

我有一个结尾处包含数字的字符串。我想在发生某些操作时将数字部分增加1

例如

var myString = 'AA11111'

increaseStringValue(myString)
# myString new value => 'AA11112'

当字符串值达到“ AA99999”时如何增加字符数,因此字符串的新值将为“ AB11111”?

5 个答案:

答案 0 :(得分:1)

您可以拆分字符和数字部分,以便分别处理。

喜欢:

function increaseStringValue(str){
    let charPart = str.substring(0,2);
    let digitPart = str.substring(2);
    digitPart = +digitPart+1
    if(digitPart >= 99999){
        digitPart = 11111;
        if(charPart[1] == 'Z'){
            if(charPart[0] == 'Z'){
                throw 'Overflow happened'
            }
            charPart = String.fromCharCode(charPart.charCodeAt(0)+1) + 'A'
        }else{
            charPart = charPart[0] + String.fromCharCode(charPart.charCodeAt(1)+1)
        }
    }

    return charPart + digitPart;
}
increaseStringValue('AA11111'); // 'AA11112'
increaseStringValue('AA99999'); // 'AB11111'
increaseStringValue('AZ99999'); // 'BA11111'
increaseStringValue('ZZ99999'); // Exception: Overflow happened

此链接将对您有所帮助:

ASCII CODES

what is a method that can be used to increment letters?

编辑:

以下功能将适合具有字符和数字动态位置的长度未知的字符串。

function increaseStringValue(str) {
    let charOverFlowed = true;
    let result = ""
    for (let i = str.length - 1; i >= 0; i--) {
        let currentChar = str[i];
        if ('123456789'.indexOf(currentChar) !== -1) {
            if (charOverFlowed) {
                currentChar = +currentChar + 1
                charOverFlowed = false;
            }
            if (currentChar > 9) {
                currentChar = 1;
                charOverFlowed = true;
            }
        } else if (charOverFlowed) {
            currentChar = String.fromCharCode(currentChar.charCodeAt(0) + 1)
            charOverFlowed = false;
            if (currentChar > 'Z') {
                if(i == 0){
                    throw 'Overflow Happened'
                }
                currentChar = 'A'
                charOverFlowed = true
            }
        }
        result = currentChar + result;
    }
    return result;
}
increaseStringValue('AAAACA')
// "AAAACB"
increaseStringValue('AAAACA1111')
// "AAAACA1112"
increaseStringValue('A1')
// "A2"
increaseStringValue('Z')
// Uncaught Overflow Happened
increaseStringValue('A1999')
// "A2111"

答案 1 :(得分:1)

 function increaseStringValue(myString){
      return myString.replace(/\d+/ig, function(a){ return a*1+1;});
 }
console.log(increaseStringValue("asg61"));

接下来的问题:

function increaseStringValue(myString){ 
    return myString.replace(/(A)(\d+)/ig, function(a, b, c){
         var r = c*1+1; return r==99999+1?"B11111":"A"+r;
    });
 }
console.log(increaseStringValue("AA99999"));

和整个过程:

function increaseStringValue(myString){ 
    return myString.replace(/([a-e])(\d+)/ig, function(a, b, c){
         var r = c*1+1; return r==99999+1?String.fromCharCode(a.charCodeAt(0)+1)+"11111":b+r;
    });
 }
console.log(increaseStringValue("AB99999"));

答案 2 :(得分:0)

请找到有用的代码段。如果这是您所期望的。

for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)
let stringNum = 'AA11111';//initialise string
let clickTriggered = ()=>{

let startString = "AA";
let newNum = ()=>{
  let numberPart = stringNum.split("AA")[1];
  let lastChar = stringNum[stringNum.length-1];
  return Number(numberPart) != NaN || Number(numberPart) <= 99999 ? Number(numberPart)+1 : 11111;
};

stringNum = `${startString}${newNum()}`
console.log(stringNum)

}

答案 3 :(得分:0)

您可以使用String#replace并在string#replace的函数回调中提供增量逻辑。

const increaseStringValue = (str) => str.replace(/\d+$/, n => n === '99999' ? 11111 : +n + 1);

console.log(increaseStringValue('AA99999'));
console.log(increaseStringValue('AA11315'));
console.log(increaseStringValue('AA11111'));

答案 4 :(得分:-2)

我用这个解决方案解决了这个问题

let app = new Vue({
  el: '#app',
  data: {
    text: "AA995"
  },
  methods: {
    addOneString: function(str) {
      var alphabet = 'abcdefghijklmnopqrstuvwxyz',
            length = alphabet.length,
            result = str,
            i = str.length,
          value = str;

        while(i >= 0) {
            var last = str.charAt(--i),
                next = '',
                carry = false;

            if (isNaN(last)) {
                index = alphabet.indexOf(last.toLowerCase());

                if (index === -1) {
                    next = last;
                    carry = true;
                }
                else {
                    var isUpperCase = last === last.toUpperCase();
                    next = alphabet.charAt((index + 1) % length);
                    if (isUpperCase) {
                        next = next.toUpperCase();
                    }

                    carry = index + 1 >= length;
                    if (carry && i === 0) {
                        var added = isUpperCase ? 'A' : 'a';
                        result = added + next + result.slice(1);
                        break;
                    }
                }
            }
            else {
                next = +last + 1;
                if(next > 9) {
                    next = 0;
                    carry = true;
                }

                if (carry && i === 0) {
                    result = '1' + next + result.slice(1);
                    break;
                }
            }

            result = result.slice(0, i) + next + result.slice(i + 1);
            if (!carry) {
                break;
            }
        }
      
      console.log("result",result);
      if (value !== result ) this.text = result;
    
    }
  }  
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div class="container" id="app">
    
  <button @click="addOneString(text)">Add one</button>
  
  </br>
  <p> {{text}} </p>
</div>