user2112700 user2112700 - 2 months ago 9
Javascript Question

Searching a text from a paragraph - Javascript?

I have written the below code to search my name from a paragraph,

/*jshint multistr:true */

text = "Blah blah blah blah blah blah Elic \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];
var l=0;
var count=0;


// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {

for(var j = i; j < (myName.length + i); j++) {
for(var k =1; k < 4; k++) {
if(text[i+k] === myName[k]){

hits.push(text[j]);
}
else {
break;
}

}
}

}
}



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


But the output is coming like
[ 'E',
'E',
'E',
'r',
'r',
'r',
'i',
'i',
'i',
'c',
'c',
'c',
'E',
'E',
'E',
'r',
'r',
'r',
'i',
'i',
'i',
'c',
'c',
'c',
'E',
'E',
'E',
'r',
'r',
'r',
'i',
'i',
'i',
'c',
'c',
'c' ]


I am sure this is because of the 3rd for loop, Please give some suggestion to fine tune this code so that the output will be like,

[ 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c' ]


Thanks in advance.

Answer

1

var res = text.match(new RegExp(myName, 'g')).join('').split('');

2

var text = "Blah blah blah blah blah blah Elic \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits   = [];
var l      = 0;
var count  = 0;
var foundName = '';  

for (var i = 0; i < text.length; i++) {
  foundName = '';

  if (text[i] === "E") {
    for (var j = 0; j < myName.length; j++) {
      foundName += text[i + j];                
    }

    if (foundName === myName) {
      for (var k = 0; k < myName.length; k++) {
        hits.push(foundName[k]);                
      }
    }
  }
}

console.log(hits);