Fault in Javascript substring matching -
i writing javascript function works endswith(),it checks if string (first argument, str) ends given target string (second argument, target).
function confirmending(str, target) { tarlen=target.length; strlen=str.length; substring = str.slice(strlen-tarlen-1, strlen); if(substring==target) {return true;} else return false; } confirmending("sangha", "ha");
take away -1
slice()
function:
function confirmending(str, target) { tarlen=target.length; strlen=str.length; substring = str.slice(strlen-tarlen, strlen); if(substring==target) {return true;} else return false; } console.log(confirmending("sangha", "ha")); console.log(confirmending("sangha", "hda"));
shortened version:
function confirmending(str, target) { var strlen = str.length; return target == str.slice(strlen - target.length, strlen); } console.log(confirmending("sangha", "ha")); console.log(confirmending("sangha", "hda"));
a version using lastindexof()
:
function confirmending(str, target) { return str.lastindexof(target) == (str.length - target.length); } console.log(confirmending("sangha", "ha")); console.log(confirmending("sangha", "hda")); console.log(confirmending("hahahahahahaha", "ha"));
Comments
Post a Comment