Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript's parseInt at end of string

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.

like image 440
sova Avatar asked Jan 11 '11 15:01

sova


Video Answer


3 Answers

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

like image 80
Kai Avatar answered Sep 22 '22 11:09

Kai


Split the number from the text, parse it, increment it, and then re-concatenate it. If the preceding string is well-known, e.g., "column", you can do something like this:

var precedingString = myString.substr(0, 6); // 6 is length of "column"
var numericString = myString.substr(7);
var number = parseInt(numericString);
number++;

return precedingString + number;
like image 34
Chris B. Behrens Avatar answered Sep 19 '22 11:09

Chris B. Behrens


Try this:

var match = myString.match(/^([a-zA-Z]+)([0-9]+)$/);
if ( match ) {
  return match[1] + (parseInt(match[2]) + 1, 10);
}

this will convert strings like text10 to text11, TxT1 to Txt2, etc. Works with long numbers at the end.

Added the radix to the parseInt call since the default parseInt value is too magic to be trusted.

See here for details:

http://www.w3schools.com/jsref/jsref_parseInt.asp

basically it will convert something like text010 to text9 which is not good ;).

like image 21
Mihai Toader Avatar answered Sep 22 '22 11:09

Mihai Toader