Reputation: 45
I have a string that contains alphabets and integer like banana12,apple123, i wanted to separate integer value from a string. I have used split() function its working perfectly for single digit number ( orange1 ) but for double digit number it is returning only single digit.
myString = banana12;
var splits = myString.split(/(\d)/);
var prodName = splits[0];
var prodId = splits[1];
the prodId should be 12 but its returning only 1 as result.
Upvotes: 2
Views: 881
Reputation: 2942
This will do it-
myString = "banana1212";
var splits = myString.split(/(\d+)/);
var prodName = splits[0];
var prodId = splits[1];
alert(prodId);
The result will be in a separate variable as you desired.
Upvotes: 4
Reputation: 5309
Try this
var myString = "banana1234";
var splits = myString.split(/(\d{1,})/);
var prodName = splits[0];
var prodId = splits[1];
alert(prodId);
fiddle: http://jsfiddle.net/xYB2P/
Upvotes: 1
Reputation: 4718
You can extract numbers like this:
var myString = "banana12";
var val = /\d+/.exec(myString);
alert(val); // shows '12'
DEMO :http://jsfiddle.net/D8L2J/1/
Upvotes: 1