Skip to content

Instantly share code, notes, and snippets.

@ready4god2513
Created November 5, 2013 20:35
Show Gist options
  • Save ready4god2513/7325771 to your computer and use it in GitHub Desktop.
Save ready4god2513/7325771 to your computer and use it in GitHub Desktop.
function nameInString(name, text)
{
var myName = name.toLowerCase(); // Lower case so we don't have to worry about case sensitivity
var text = text.toLowerCase(); // Lower case so we don't have to worry about case sensitivity
var nameLen = myName.length; // Assign to variable so we don't have to keep checking
var hits = [];
var found = false;
for(i = 0; i < text.length; i++)
{
// Check to see if we have a letter that starts your name. Lower case so we don't have to worry about case sensitivity
if(text[i] == myName[0])
{
// Now we will grab the next n letters. Where n is the length of your name
// Start from the position of the outer loop.
found = true;
for(j = i, c = 0; j < (nameLen + i); j++, c++)
{
if(text[j] != myName[c])
{
found = false;
}
}
if(found)
{
hits.push([i, i + nameLen]); // Push the starting and ending index of your name
}
}
}
if(hits.length)
{
console.log("Your name " + myName + " was found in the following positions: ");
for(i = 0; i < hits.length; i++)
{
console.log(hits[i][0] + " - " + hits[i][1]);
}
}
else
{
console.log("Your name was not found");
}
}
// Test names with capitalization
nameInString("Ryan", "Lorem ipsum Ryan sit amet, consectetur adipiscing elit. Nulla Ryan venenatis Ryan. Sed ac tincidunt");
nameInString("Brandon", "Lorem ipsum Ryan sit amet, consectetur adipiscing elit. Nulla Ryan venenatis Ryan. Sed ac tincidunt");
// Test names without capitalization
nameInString("ryan", "Lorem ipsum Ryan sit amet, consectetur adipiscing elit. Nulla Ryan venenatis Ryan. Sed ac tincidunt");
nameInString("brandon", "Lorem ipsum Ryan sit amet, consectetur adipiscing elit. Nulla Ryan venenatis Ryan. Sed ac tincidunt");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment