tags:

views:

123

answers:

2

Hi,

How can I make this function a little more 'defensible' against null/empty strings?

function getSecondPart(str) {
    return str.split('-')[1];
}
+7  A: 
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
Paolo Bergantino
That's about as defensive as it's gonna get :x
Paolo Bergantino
Don’t make it too complicated.
Gumbo
Yeah. I simpled it up a bit.
Paolo Bergantino
Oh, so you like my proposal …
Gumbo
Haha, I thought of it before seeing yours, but I'll give you an upvote if it'll make ya feel better :)
Paolo Bergantino
You should switch != for !== on line 3 and == for === on line 4.
Kit Sunde
Use "typeof str === 'undefined'" instead since "undefined" is just a global variable that can be overwritten (undefined="a string"). Also use "!==" on line 3 and "< 0" or "=== -1" on line 4.
some
+1  A: 

I’d say:

function getSecondPart(str) {
    if (typeof str !== "string" || str.indexOf("-") === -1) return false;
    return str.split("-")[1];
}
Gumbo