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.

8
  • 1
    what if string is something like "banana12with34" ..? what should be the output..? Commented Jun 4, 2014 at 5:31
  • Your question is answered here: stackoverflow.com/questions/3370263/… Commented Jun 4, 2014 at 5:32
  • Use /(\d+)/ instead! Commented Jun 4, 2014 at 5:36
  • @Bergi I believe split itself is a bad choice here, what do you think? Commented Jun 4, 2014 at 5:37
  • 1
    @thefourtheye: Depends on whether myString is a sequence of multiple names & ids. Sure, .match(/([a-z]+)(\d+)/i) might be the better choice if not. Commented Jun 4, 2014 at 5:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

2 Comments

Thank you,it is working what if i want characters in a separate variable.
@NoorFathima, could you share us an example of separate variable ? What you would like to acheive?
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.