如何使用数字增加字符串?

时间:2015-12-06 00:51:33

标签: javascript

我需要增加一个与此类似的值:

A001 becomes A002
A999 becomes B001
B001 becomes B002
etc
Z999 becomes A001 

我可以增加这样的整数:

var x = 5;
x++;

收益率x = 6

我可以像这样增加一个角色:

var str = 'A';
str = ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
if (str =='1A') {
  str = 'A';
}

产生字母表中的下一个字符。

此代码似乎有效,但我不确定它是最好的方法吗?

var str = 'Z999';

if (str == 'Z999') {
   results  = 'A001';
}
else {
  var alpha = str.substring(0,1);
  num = str.substring(1,4);

  if (alpha != 'Z' && num == '999') {
     alpha= ((parseInt(alpha, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
  }

  num++;
  var numstr = num + "";
  while (numstr .length < 3) numstr = "0" + numstr ;

  if (numstr == 1000) {
    numstr  = '001';
  }

  results = alpha + numstr;
}

结果似乎给出了正确的答案。是

2 个答案:

答案 0 :(得分:1)

您可以使用parseInt(input.match(/\d+$/), 10)提取字符串末尾的数字,并使用input.match(/^[A-Za-z]/)来检索开头的单个字符。

相应地增加和填充数字,并通过检索字符的字符代码并递增该数字,在数字超过999时增加字符。

String.fromCharCode(letter.charCodeAt(0) + 1);

完整代码/示例:

&#13;
&#13;
function incrementNumberInString(input) {
  var number = parseInt(input.trim().match(/\d+$/), 10),
      letter = input.trim().match(/^[A-Za-z]/)[0];

  if (number >= 999) {
    number = 1;
    letter = String.fromCharCode(letter.charCodeAt(0) + 1);
    letter = letter === '[' ? 'A': (letter === '{' ? 'a' : letter);
  } else {
    number++;
  }
  
  number = '000'.substring(0, '000'.length - number.toString().length) + number;

  return letter + number.toString();
}

document.querySelector('pre').textContent = 
  'A001: ' + incrementNumberInString('A001')
+ '\nA999: ' + incrementNumberInString('A999')
+ '\nB001: ' + incrementNumberInString('B001')
+ '\nB044: ' + incrementNumberInString('B044')
+ '\nZ999: ' + incrementNumberInString('Z999');
&#13;
<pre></pre>
&#13;
&#13;
&#13;

输出:

  

A001:A002

     

A999:B001

     

B001:B002

     

B044:B045

     

D7777:E001

答案 1 :(得分:0)

尝试将A-Z存储在数组中,String.prototype.replace()RegExp /([A-Z])(\d+)/g匹配,以匹配大写字符,数字字符。如果达到"Z999",不确定预期结果是什么?

&#13;
&#13;
var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");

var spans = document.querySelectorAll("span");

function count(el) {

  var data = el.innerHTML.replace(/([A-Z])(\d+)/g, function(match, text, n) {

    var _text, _n;

    if (Number(n) === 999) {
       _text = arr[ arr.indexOf(text) + 1 ];
    } else {
       _text = text
    };
    // `"Z999"` condition ?
    if (_text === undefined) {
        return "<mark>" + text + n + "</mark>"
    }

    _n = Number(n) + 1 < 1000 ? Number(n) + 1 : "001";

    if (n < 10) {
      return _text + n.slice(0, 2) + _n
    };
    
    if (n < 100) {
      return _text + n.slice(0, 1) + _n
    } else {
      return _text + _n
    }
  });
  
  el.innerHTML = data
}

for (var i = 0; i < spans.length; i++) {
  count(spans[i])
}
&#13;
<span>A001</span>
<span>A999</span>
<span>B001</span>
<span>C999</span>
<span>D123</span>
<span>Z999</span>
&#13;
&#13;
&#13;