JavaScript: Get the successor of a string
JavaScript String: Exercise-48 with Solution
String Successor
Write a JavaScript function to get the successor to a string.
Note: 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.
Example:
string.successor("abcd") == "abce"
string.successor("THX1138") == "THX1139"
string.successor("<
string.successor("1999zzz") == "2000aaa"
string.successor("ZZZ9999") == "AAAA0000"
Test Data:
console.log(successor('abcd'));
console.log(successor('3456'));
"abce"
"3457"
Sample Solution:
JavaScript Code:
Output:
abce 3457
Explanation:
The above JavaScript code defines a function "successor(str)" that generates the successor of a given string. Here's a breakdown:
- The function takes a string 'str' as input.
- It initializes variables including the alphabet, the length of the alphabet, the result (initially set to the input string), and the index variable for iterating through the string from right to left.
- The function then enters a loop that iterates through each character of the string from right to left.
- Inside the loop:
- It checks if the current character is a letter or a digit.
- If it's a letter, it finds the index of the character in the alphabet and determines the next character in the alphabet. It handles uppercase characters by preserving case.
- If it's a digit, it increments it by 1, handling carry operations if necessary.
- It updates the result string with the next character or digit.
- If there's no carry operation, the loop exits.
- Finally, the function returns the resulting string.
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that computes the successor of a string by incrementing its rightmost alphanumeric character.
- Write a JavaScript function that handles carry-over when incrementing characters in a string successor calculation.
- Write a JavaScript function that validates the input and returns the original string if no alphanumerics are found.
- Write a JavaScript function that returns the successor of a string while preserving the case of each character.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to test whether a string ends with a specified string.
Next: Write a JavaScript function to get unique guid (an acronym for 'Globally Unique Identifier’) of the specified length, or 32 by default.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics