Juan
Juan

Reputation: 193

Is it possible to summarize 3 conditionals in one function

I have created a script that removes part of a string if any of these characters are present:, & and / I have created a function that returns the string with the portion of text I need. But I want to join all conditionals in the function, since it is not good technique to have 3 IFs.

Example:

currentArtist = 'Dimitri Vegas & Like Mike,Paris Hilton/Dimitri Vegas'

Return: Dimitri Vegas

Example2:

currentArtist = 'Tiësto, Jonas Blue , Rita Ora'

Return: Tiësto

this.refreshLyric = function(currentArtist) {
    if (currentArtist.includes("&")) {
        let i = currentArtist.indexOf("&");
        var currentArtist = cleanText(currentArtist, i);
    } 
        if (currentArtist.includes("\/")) {
            let i = currentArtist.indexOf("\/");
            var currentArtist = cleanText(currentArtist, i);
        } 
            if (currentArtist.includes(",")) {  
                let i = currentArtist.indexOf(",");
                var currentArtist = cleanText(currentArtist, i);
            } 
}       

function cleanText(artist, index){
 let currentArtist = artist.substring(0,index);
 return currentArtist.trim();
}

Upvotes: 1

Views: 55

Answers (2)

Always Helping
Always Helping

Reputation: 14570

You can simply use String#split() function to get your desired output! Its simple and you are replacing anything from your original string or words you have.

split() return an array of words that matched the condition.

Live Demo:

let currentArtist = 'Dimitri Vegas & Like Mike,Paris Hilton/Dimitri Vegas'.split('&')[0].trim();
let currentArtist2 = 'Tiësto, Jonas Blue , Rita Ora'.split(',')[0].trim();
console.log(currentArtist) //Dimitri Vegas 
console.log(currentArtist2) //Tiësto

Upvotes: 1

Hao Wu
Hao Wu

Reputation: 20867

Maybe using a regex is an easier way to do this:

const regex = /[&\/,].*$/;
let currentArtist;

currentArtist = 'Dimitri Vegas & Like Mike,Paris Hilton/Dimitri Vegas';
currentArtist = currentArtist.replace(regex, '');
console.log(currentArtist);


currentArtist = 'Tiësto, Jonas Blue , Rita Ora';
currentArtist = currentArtist.replace(regex, '');
console.log(currentArtist);

Upvotes: 2

Related Questions