Search code examples
javascriptnode.jssplitseparator

Split Artist - Title JavaScript


I have the following script:

const Parser = require('../src');

const radioStation = new Parser('http://stream.com/live_32.aac');

radioStation.on('metadata', function(metadata) {
    console.log([metadata.StreamTitle]);
});

The output on the console is:

Artist - Title

I want to split the Artist and Title.

I found something like:

str.split(separator)

But it's not working correct.

Does any one have a solution?


Solution

  • You were write, split() creates from your string an array of 2 elements : ["Artist "," Title"].

    As you can see there are whitespaces. trim() removes those whitespaces (map is used to loop through all the elements of the array)

    var values = "Artist - Title".split('-').map(i=>i.trim());
    // creates : values = ["Artist","Title"]
    var artist = values[0];
    var title = values[1];
    
    console.log(artist); // "Artist"
    console.log(title);  // "Title"

    If you want to avoid using trim(), you can split on " - " instead of just "-"

     var values = "Artist - Title".split(' - ');
        // creates : values = ["Artist","Title"]
        var artist = values[0];
        var title = values[1];
    
        console.log(artist); // "Artist"
        console.log(title);  // "Title"