Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Created November 7, 2019 20:30
Show Gist options
  • Save trafficinc/f8f5472d29f90167a424b84d8eb0e463 to your computer and use it in GitHub Desktop.
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.
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