How do I split a path file string in different parts and then print it out with JavaScript?

Viewed 141

I am working on a project for fun using IndexOf, splitting... and I am trying to get my code to print out the content before the ":" and after for each line. Instead I'm getting issues combining 2 pieces of code by going to each number of lines and splitting them. I’m looking for maybe a for/while loop so it grabs each part for each line and assigns it to the var (origin,color). (I eventually want to call var - origin,color in my later script.

I have tried looking around on guides but haven't found something to cement the 2 ideas together. Might be easy but Im just missing it...

EDIT: [From CODE 1]-

console.log(lines);

Gives:

[ 'Level1:Blue', 'Level2:Red', 'Level3:Green' ]

CODE 1

var fs = require('fs');

var path = 'file.txt';    

var text = fs.readFileSync(path).toString(); 

var lines = text.split('\n'); 

var newlines_count = lines.length;

var i=0; //looping through the lines

var count=1; //counts how many

var linechange=1;


for (; i < newlines_count; ) 

{

linechange = lines[i];

  console.log(lines);

  console.log(count);

  i++;

//counts how many lines in the string

}

CODE 2

var str = "Level1:Blue";

var long=str.length;

var place=str.indexOf(":")

//console.log(place)

var origin=str.slice(0,place);

var color=str.slice(place+1,long);

console.log(origin);

console.log(color);

//splits the content before and after the ":"
//Code 2 Doesn't have the long string from Code 1 so the variable "long" wont really work

The info in the .txt file is(can be anything w/ ":"):

Level1:Blue

Level2:Red

Level3:Green

...(keeps going as I add more)


What I'm trying to get printed out:

Level1

Blue

Level2

Red

Level3

Green

1 Answers

You could split the string and join it with some linefeeds and make your output.

function splitPrint(string) {
    var parts = string.split(':');
    console.log(parts.join('\n\n'));
}

splitPrint('Level1:Blue');

Output line for line

function splitPrint(string) {
    var parts = string.split(':');
    parts.forEach(part => console.log(part));
}

splitPrint('Level1:Blue');

Related