nodejs - how to remove part of a string after a delimiter

202 views Asked by At

I'm using this code in a nodejs script to push some elements inside an array for list question type of inquirerjs.

for (let [index, torrent] of results.entries()) {
    if (torrent.seeds > 0 && torrent.peers > 0) {
        filesList.push(`${torrent.title} s:${torrent.seeds} p:${torrent.peers}`);
        filesDetails.push(torrent);
    } else {
        results.splice(index, 1);
    }
}

As you can see I'm adding the s:value and the p:value after the filename to inform the user about seeds and peers of a file. When the user select a file from the list, I'm searching into the array of objects to find the file and serve it back. If I don't add the s:value and the p:value to the file name, all is working as expected but since I need to provide this informations, how I can remove them from the file name before looping the array?

This is the code I'm using at the moment to find the right file into the objects array

const selectedTorrent = [];
for (let f of filesDetails) {
    if (f.title === availableTorrents.selected) {
        selectedTorrent.push(f);
    }
}
1

There are 1 answers

3
Drago96 On BEST ANSWER

It is not very clear how "filesList" is used in the second snippet, but to answer the question in the title, you can remove the part starting from "s:" using a combination of the string built-in functions indexOf and substring:

let title = `Torrent title s:${torrent.seeds} p:${torrent.peers}`;

let strippedTitle = title.substring(0, title.indexOf(" s:")); // returns "Torrent title"

indexOf: MDN Docs

substring: MDN Docs