The problem is the following: I have to return the numeral part of the string added +1 , what I get back also has to be a string. For example:
incrementString("foobar000") // "foobar001"
incrementString("foo") // "foo1"
incrementString("foobar001") // "foobar002"
incrementString("foobar99") // "foobar100"
incrementString("foobar099") // "foobar100"
incrementString("") // '1'
incrementString("foobar00999") // "foobar01000"
incrementString("009") // '010'
I tried to solve it, but I couldn't. This is a section of my code:
var strng = "foobar000"; // esto podría ser strng ='foobar001'
var numero = strng.slice(-1);
var convertido2 = parseInt(numero) +1;
console.log(strng.replace(numero,convertido2));
I have made a small function that does what you want. The idea is to keep whatever digits are at the end of the string, remove them from the initial string, increment the value by 1, add 0s to them in front, and add them back to the string.
Here you can see the commented and running code:
You have to solve two problems.
First , given the string, get the numeric part and the non-numeric part. You can do this with a regular expression:
This means: "catch all occurrences of a non-numeric character in group 1, and all occurrences of a numeric character before the end of the string in group 2".
This means that it
foobar000
returnsfoobar
in group1 and000
in group 2.It also means that it
123foobar000
returns the same result, since the first three numbers are not at the end of the string.It also means that given a numeric
12345
-only string group1 is""
and given a string without numbers, group2 is""
(empty strings).The use of the * in the regular expression means that I catch zero or more occurrences of the pattern.
Both capturing groups are of type text.
Your second problem is that to add 1, you have to do the logic:
NaN
For point 4, I declared a helper function that puts zeroes at the beginning until it meets a minimum length.
This is one way to solve it. Another way, for example if they wanted it to be
123foobar0010
returned ,123foobar0011
would be to ignore the first group and in the field use a substring of the original text removing the last N digits, where N is the length of the number.If you notice, I defined a variable
subcadena
that is what I put above. If that is the desired result, then where it says:should say