Hi,
How can I make this function a little more 'defensible' against null/empty strings?
function getSecondPart(str) {
return str.split('-')[1];
}
Hi,
How can I make this function a little more 'defensible' against null/empty strings?
function getSecondPart(str) {
return str.split('-')[1];
}
function getSecondPart(str) {
if(str === undefined ||
typeof str != 'string' ||
str.indexOf('-') == -1) return false;
return str.split('-')[1];
}
console.log(getSecondPart({}); // false
console.log(getSecondPart([]); // false
console.log(getSecondPart()); // false
console.log(getSecondPart('')); // false
console.log(getSecondPart('test')); // false
console.log(getSecondPart('asdf-test')); // test
I’d say:
function getSecondPart(str) {
if (typeof str !== "string" || str.indexOf("-") === -1) return false;
return str.split("-")[1];
}