t4thilina
t4thilina

Reputation: 2197

Separate a string into numeric values

I have a string like 1.1.2 . What I need is I need to separate the numeric values and take the values 1, 1, 2 separately. Better If I can put the 3 values into an array. Could someone please suggest me a way.

Ex: If the value is 1.2 I should be able to get 1 and 2 separately.

Then If it is 1.10 should be able to get 1 and 10 separately..

1.10.11 then the values must me 1 , 10 and 11

Upvotes: 0

Views: 70

Answers (5)

japrescott
japrescott

Reputation: 5015

this can be done very simply;

var string="1.2.13";
var split=string.split(".");
console.log(split); //[1,2,13]
console.log(split[1]) //2

Upvotes: 1

Anthony Porter
Anthony Porter

Reputation: 152

You can use the string .split method with a period as the delimiter. It will return an array of strings by default .split"."

Upvotes: 1

Charlie74
Charlie74

Reputation: 2903

Using split, you can do something like this...

var s = "1.4.2.6.10";
nums = s.split('.');

alert (nums[4]);

nums is an array, and you can access any value of the array using nums[0], nums[1], etc.

DEMO

Upvotes: 1

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

string = "1.1.2"
a = string.split(".")

will split it to [1,1,2]

if you also want to parse it to int do the following

for(i=0;i<a.length;i++){
  a[i] = parseInt(a[i])
}

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You can use split()

var data = "1.10.11";
var arr = data.split('.');
for(i=0; i<arr.length;i++)
    alert(arr[i])

DEMO

If you to use it as int, you can convert it using parseInt()

Upvotes: 2

Related Questions