Quote:
Originally Posted by Philip M
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!