在红宝石中,
"a".next [or] "a".succ # => "b"
"aa".next # => "ab"
"z".next # => "aa" # two a's after one z
如何在 Javascript 中使用它?就像是:
incr_str("aaa") ===> aab
incr_str("zzz") ===> aaaa
在红宝石中,
"a".next [or] "a".succ # => "b"
"aa".next # => "ab"
"z".next # => "aa" # two a's after one z
如何在 Javascript 中使用它?就像是:
incr_str("aaa") ===> aab
incr_str("zzz") ===> aaaa
谷歌搜索“Ruby string succ Javascript”会返回Devon Govett 的这个要点,称为“JavaScript 中 Ruby 的 string.succ 方法的实现”,这似乎是你所追求的......
/*
* An implementation of Ruby's string.succ method.
* By Devon Govett
*
* Returns the successor to str. The successor is calculated by incrementing characters starting
* from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the
* string. Incrementing a digit always results in another digit, and incrementing a letter results in
* another letter of the same case.
*
* If the increment generates a carry, the character to the left of it is incremented. This
* process repeats until there is no carry, adding an additional character if necessary.
*
* succ("abcd") == "abce"
* succ("THX1138") == "THX1139"
* succ("<<koala>>") == "<<koalb>>"
* succ("1999zzz") == "2000aaa"
* succ("ZZZ9999") == "AAAA0000"
*/
function succ(input) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz',
length = alphabet.length,
result = input,
i = input.length;
while(i >= 0) {
var last = input.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;
}
}
return result;
}
我找到了 RubyJs 库。请检查一下。
<script src="ruby.min.js"></script>
<script>
var str = R("aaa");
alert(str.next());
</script>
String.fromCharCode()
和的组合"".charCodeAt()
应该相当直接地实施。
var FIRST = 97,
LAST = 122;
function next (string) {
var lastChar = string[string.length - 1];
string = string.substring(0, string.length - 1);
if(lastChar.charCodeAt(0) >= LAST) {
// make last char a and append a
lastChar = String.fromCharCode(FIRST) + String.fromCharCode(FIRST);
}
else {
// Increase last char
lastChar = String.fromCharCode(lastChar.charCodeAt(0) + 1);
}
return string + lastChar;
}
非常快速和肮脏并且行为有点奇怪(zzz -> zzaa 而不是 zaaa 或 zzza,不确定哪种行为是最好的),但它显示了你如何去实现它(而且 atm 我没有时间写一个更精致的答案)。