View Single Post
Old 12-18-2012, 08:06 PM   PM User | #8
Entity_
New Coder

 
Join Date: Dec 2012
Location: Ingerlund
Posts: 62
Thanks: 8
Thanked 4 Times in 4 Posts
Entity_ is an unknown quantity at this point
Quote:
Originally Posted by Philip M View Post
Not using a regular expression:-

Code:
<script type = "text/javascript">

text = "Blah blah blah blah blah blah Tim \
blah Terry blah blah Tim blah Thomas blah Tim blah blah \
blah blah blah blah blah Tim";

var myName = "Tim";
var hits = [];
var n = "";
for (var i = 0; i < text.length; i++){
if (text.charAt(i)== "T") {
for (var j = i; j < (myName.length+i); j++) {
n += text.charAt(j);
}
if (n == myName) {
hits.push(n);
}
n = "";
}
}


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

</script>
myName.length + i means the next 3 characters following the current position which is index i. As devnull69 has explained.
text(i) is undefined. Use text.charAt(i) instead.

While this finds Tim but not Thomas, it will also find Timothy and Timpson so not very reliable.

The regex should read
Code:
var hits = text.match(/\bTim\b/g).length;  // Tim as a whole word only - not Timothy or Timpson
alert (hits);


And thanks a lot for your help too mate, but I'm not looking for better code, I just wanted to know why I had to add + i to the for! Thanks anyway!
Entity_ is offline   Reply With Quote