Using JavaScript's parseInt at end of string

sova picture sova · Jan 11, 2011 · Viewed 7.7k times · Source

I know that

parseInt(myString, 10) // "Never forget the radix"  

will return a number if the first characters in the string are numerical, but how can I do this in JavaScript if I have a string like "column5" and want to increment it to the next one ("column6")?

The number of digits at the end of the string is variable.

Answer

Kai picture Kai · Jan 11, 2011
parseInt("column5".slice(-1), 10);

You can use -1 or -2 for one to two digit numbers, respectively.

If you want to specify any length, you can use the following to return the digits:

parseInt("column6445".match(/(\d+)$/)[0], 10);

The above will work for any length of numbers, as long as the string ends with one or more numbers