Reputation: 115
Using javascript prompt I get two parameters like, search string and search keyword, then search for the keyword and get the number of items found. Then need to show them on the page. Seems to mistake I have made.
<html>
<head>
<script type = "text/javascript">
var counter = 0;
var enter = prompt("Enter your String:");
var search = prompt("Enter words to search:");
var b = search.length;
var a = enter.length - search.length;
for (var y = 0; y <= a; y++)
{
if(b <= enter.length){
if(enter.substring(y,B))
{
counter = counter + 1;
}
b++;
}
else{
document.write("<p>" + "ERROR" + "</p>");
}
document.write("<p>" + "your word:" + enter + "</p>");
document.write("<p>" + "word use:" + counter + "</p>");
</script>
<body>
</body>
</head>
</html>
Upvotes: 0
Views: 185
Reputation: 2200
Upvotes: 1
Reputation: 539
You can also use indexOf:
var counter = 0;
var enter = prompt("Enter your String:");
var search = prompt("Enter words to search:");
var start = 0;
while(1){
start = enter.indexOf(search,start);
if(start==-1) break;//if nothing found
start++;//next start = current occurrence + 1
counter++;
}
document.write("<p>" + "your word:" + enter + "</p>");
document.write("<p>" + "word use:" + counter + "</p>");
Upvotes: 0
Reputation: 25091
As Sameera Thilakasiri has rightly pointed out, your code is sloppy. If that works for you, great (I suppose), but other people who look at your code may have a hard time following it. Further, sloppy code leads to mistakes that would otherwise be easily caught.
For instance, you have not closed the for
loop, which would easily be seen in nicely formatted code.
Beyond the open for
loop, the only other problem I see (syntactically) is that JavaScript is a case-sensitive language, which means that b
is different from B
, which is why your script throws the 'Uncaught ReferenceError: B is not defined' on the line if (enter.substring(y,B)) {
.
Try closing your for
loop and using a lowercase b
on the offending line. Once that is done, you only have to fix the logic errors.
Happy coding.
Upvotes: 0