2

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.

3 Answers3

4

This will do it-

myString = "banana1212";
    var splits = myString.split(/(\d+)/);
    var prodName = splits[0];
    var prodId = splits[1];
alert(prodId);

http://jsfiddle.net/D8L2J/2/

The result will be in a separate variable as you desired.

benomatis
  • 5,536
  • 7
  • 36
  • 59
halkujabra
  • 2,844
  • 3
  • 25
  • 35
1

You can extract numbers like this:

var myString = "banana12";
var val = /\d+/.exec(myString);
alert(val); // shows '12'

DEMO :http://jsfiddle.net/D8L2J/1/

naota
  • 4,695
  • 1
  • 18
  • 21
1

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/

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97