Created
November 7, 2019 20:30
-
-
Save trafficinc/f8f5472d29f90167a424b84d8eb0e463 to your computer and use it in GitHub Desktop.
JavaScript, finds first occurrence of a string within another, case insensitive. Inspiration from the similar PHP function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function stristr (haystack, needle, bool) { | |
var pos = 0; | |
haystack += ''; | |
pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase()); | |
if (pos == -1) { | |
return false; | |
} else { | |
if (bool) { | |
return haystack.substr(0, pos); | |
} else { | |
return haystack.slice(pos); | |
} | |
} | |
} | |
console.log( stristr('Aenean et iaculis odio, at iaculis libero. Donec ultricies dui et congue lobortis. potenti.', 'dui') ); | |
// will return `dui et congue lobortis. potenti.` | |
console.log( stristr('Aenean et iaculis odio, at iaculis libero. Donec ultricies dui et congue lobortis. potenti.', 'dui', true) ); | |
// will return `Aenean et iaculis odio, at iaculis libero. Donec ultricies ` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment