Sachin
Sachin

Reputation: 217

logic to split this in javascript?

I have the following text,

              Name:Jon
               Age:25
              Gender:Male

how to split this to get the following result,

              Jon
              25
               Male

if i use this,

           var results = file.split(":");

i get results[0]=Name, results[1]=JonAge, results[2]=25Gender, and when i give,

            var results = file.split("\n");

i get results[0]=Name:Jon, results[1]=Age:25,...

but i couldn't get the above, how to check for either a colon or a new line at the same time ?

Upvotes: 0

Views: 191

Answers (3)

Ethan Brown
Ethan Brown

Reputation: 27282

You need to split first on the newline, then the colon:

file.split('\n').map(function(line){return line.split(':')[1];})

This could be accomplished with a loop, obviously, but the map function makes it nice and neat.

You could also use a regular expression:

file.match(/[^:]+$/gm)

Finally, you can extend the functionality of arrays by creating a split function that works on arrays:

Array.prototype.split = function(s) { 
    return this.map( function(x) { return.x.split(s); } ); 
}

Then you can chain your splits and you'll get an array of arrays:

var results = file.split('\n').split(':');
console.log( 'Name: ' + results[0][1] );
console.log( 'Age: ' + results[1][1] );
console.log( 'Gender: ' + results[2][1] );

Your choice of method depends a lot on how "safe" you want to be. I.e., are you concerned about malformed input or colons in the field names or values....

Upvotes: 4

Lix
Lix

Reputation: 47956

This can be accomplished with two steps, first you'll want to split the text by newline:

lines = str.split( '\n' )

Then iterate over each line and split each one by a colon:

final = {};
for ( pair in lines ){
  var split = lines[ pair ].split( ':' );

  var name = split[ 0 ].trim(); //cleaning out any whitespacve
  var value = split[ 1 ].trim(); //cleaning out any whitespacve

  final[ name ] = value;
}

final is now:

Object {Name: "Jon", Age: "25", Gender: "Male"}

Upvotes: 0

19greg96
19greg96

Reputation: 2591

You can't. Use a for loop.

var r = file.split("\n");
var results = [];
for (var i = 0; i < r.length; i++) {
    results[i] = r[i].split(":")[1];
}

Upvotes: 1

Related Questions