1

I am trying to split ZIN.2.1 into 3 variables
var1=zin
var2=zin.2
var3=zin.2.1

So far i have tried

var text = "zin.2.1";
var splitted = text.split(".");
console.log(splitted);
console.log(splitted[0]);

</script>

output: ["zin", "2", "1"]
"zin"

Is there anything i can try to achieve. I am new to js

Aakash Doshi
  • 202
  • 1
  • 3
  • 14

2 Answers2

1

You can use the javascript map() function to loop through your array and build up a string of each value into a new array:

var text = "zin.2.1";
var splitted = text.split(".");

// build this string up
var s = "";

var splitted2 = splitted.map(function(v) {

    // don't add a . for the first entry
    if(s.length > 0) {
        s += '.';
    }

    s += v;

    // returning s will set it as the next value in the new array
    return s;
});

console.log(splitted2);
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
1

Try this one

function mySplit(text) {

  var splitted = text.split("."), arr = [];

  arr.push(splitted[0]);
  arr.push(splitted[0] + '.'+ splitted[2]);
  arr.push(text);

 return arr;

}

var text = "zin.2.1";

console.log(mySplit(text));

Output:

["zin", "zin.1", "zin.2.1"]

DEMO

Nitish Kumar
  • 4,850
  • 3
  • 20
  • 38
  • I am having hard time storing the array value. var first = arr[0]; var second= arr[1]; "ReferenceError: arr is not defined Am i doing anything wrong? – Aakash Doshi Dec 08 '14 at 08:09