Ways to search my name only



Hi there,

I used this method to look for only my name in the text. What do you think of it ? I was wondering if there is a more direct way to make sure that only my name come out (without having to type a new line of code for each letter of my name).

Thank you !

/*jshint multistr:true */

var text = "La justice rouvre Christiane l’instruction \ dans l’affaire de corruption et de trafic d’influence à la Christiane Christiana Cour de \ cassation.";

var myName = "Christiane";

hits = [];

for (i=0; i<=text.length; i++) {
        if(text[i+1] === "h") {
            if(text[i+2] === "r") {
                if(text[i+3] === "i") {
                    if(text[i+4] === "s") {
                        if(text[i+5] === "t") {
                            if(text[i+6] === "i") {
                                if(text[i+7] === "a") {
                                    if(text[i+8] === "n") {
                                        if(text[i+9] === "e") {
            for(j=i; j<=i+myName.length; j++){hits.push(text[j])}}}}}}}}}}}

if (hits.length === 0) {
    console.log("Your name wasn't found!");}
else {


you could check for your first and last letter of your name?

if (text[i] === "C" && text[i+name.length - 1] === "e")

it is very unlikely that the first and last letter of your name, would match another word.

If the && isn't covered yet, just simple make two if statements. There are other tricks as well, but this should be a good first step


Thank you stetim94 ! Great to learn about the &&, and thanks for your method.


hasn't that been covered yet? You can also just nest them:

if (text[i] === "C"){
  if(text[i+name.length - 1] === "e"){


might performance wise even better. Either way, to check each letter of your name is quit an extensive operation.


Not covered yet indeed, it seems very practical though.
I could also just have

if(text[i]==="C") && (text[i+9] === "e") right ?

I am a bit confused by this actually : if(text[i+name.length - 1] === "e"

Isn't i+name.length my name + an extra character if i is "C" ?


no, you can't. You can have:

if(text[i]==="C" && text[i+9] === "e")


if((text[i]==="C") && (text[i+9] === "e"))

either way, the && operator should be inside the condition (between the brackets)

no, lets say i is 17. And at index 17 is C. Your name is 10 letters long. but the e is at index 26. So myName.length is 10, but you need minus one. It is for the same reason you do i+9, despite your name being 10 letters long


I see, that makes sense. Thank you!