javascript - Testing starting chars of two sentences against eachother -


i'm working way through eloquent javascript , ran practice:

write function called startswith takes 2 arguments, both strings. returns true when first argument starts characters in second argument, , false otherwise.

here's answer gave:

function startswith(string, pattern) { return string.slice(0, pattern.length) == pattern; }  show(startswith("rotation", "rot")); 

but wanted more thorough program take start characters chars , test them in each sentence , spit out whether starting characters same in each sentence. i'm new javascript , programming, appreciated! here's thought work:

var sentenceone = "pretty kitty doesn't you!"; var sentencetwo = "preachy cat loves you."; function startswith(chars) {   return (sentenceone.slice(0, chars.length) == chars) == (sentencetwo.slice(0, chars.length) == chars); } show(startswith("pre")); 

the answer given pretty thorough. given 2 sentences do:

var sentenceone = "pretty kitty doesn't you!"; var sentencetwo = "preachy cat loves you.";  show(startswith(sentenceone, "pre") === startswith(sentencetwo, "pre")); 

you don't need entirely new function checks whether 2 strings start same pattern. see demo: http://jsfiddle.net/p3unn/1/


another way is, given 2 sentences , pattern test whether starting characters same:

function startwith(sentenceone, sentencetwo, pattern) {     return !(sentenceone.indexof(pattern) || sentencetwo.indexof(pattern)); } 

now do:

show(startwith(sentenceone, sentencetwo, "pre")); 

see demo: http://jsfiddle.net/p3unn/2/


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -