Repetition via for loop based on prompt output - javascript

So essentially what I'm trying to do is to figure out how to repeat a line x number of times based on a prompt's output.
i.e
<script>
var favnumber = Number(prompt("What is your favorite number?"))
for(var i=0;i<favnumber;i++){
System.out.println(name + "is bad at javascript");
}
</script>
any idea whats wrong?

JavaScript is not Java. So there is no function System.out.println() unless you define it.
To output you hav either to user the DOM, console or alert.
The later might look like this:
<script>
var favnumber = Number(prompt("What is your favorite number?"));
var name = 'Bob';
for(var i=0;i<favnumber;i++){
alert(name + " is bad at javascript");
}
</script>
Besides, try to get used to end every command with ;. Otherwise you run into many weird problems as a JavaScript beginner - and later as well.

JavaScript is not Java, so System.out.println doesn't have any special meaning. You have two options here: to use console.log(), or to use document.write().
I recommend you use console.log(), as it doesn't mess with the current page's HTML structure:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
console.log(name + ' is not Java');
}​
You'll need to open up your browser's JavaScript console to see those messages.
Using document.write() is a bit more cumbersome:
var favnumber = parseInt(prompt("What is your favorite number?"), 10);
var name = 'JavaScript';
for (var i = 0; i < favnumber; i++) {
document.write(name + ' is not Java');
document.write('<br />');
}​
Demo: http://jsfiddle.net/HC3Y2/

Related

Is there any way to print multiple lines in JS alert box using loop?

Hey guys I want to ask if there is any way to write multiple lines in one JS alert box using for loop?
I WANT TO HAVE OUTPUT LIKE THIS WITH ONE STRING VARIABLE AND ANY LOOP,
HOW CAN I HAVE OUTPUT LIKE THIS WITH ABOVE MENTIONED REQUIREMENTS?
Use \n
alert("String 1\nString 2");
var p = '';
for (var i = 1; i < 5; i++) {
p+= "string " + i + '\n'
}
alert(p)

Issue with passing property through function

First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.
var student={FirstName:"", LastName:""};
var studentlist=[];
var i=0;
function generatePassword() {
var length = 4,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
function Register() {
var next="Yes";
while (next="Yes"){
student.FirstName=prompt("Please enter the name");
student.LastName=prompt("Please enter the last name");
studentlist.push(student);
document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
"<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
next = prompt ("Do you want to add more data?", "Yes")
i++;
}
}
Two mistakes:
var student={FirstName:""; LastName:""};
Should be -> var student={FirstName:"", LastName:""};
var i==0; -> var i = 0;
Try after changes and tell me if it works ;d
Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.

Printing each value of an array on a separate line Javascript

I have a program that involves Javascript to allow for interaction with a webpage. It's a baseball site so what I am doing is prompting the user to enter a month. The user can enter a number, like 6 for June, or the name of the month itself and the program will display all the games they are playing that month.
The way I did this was to create an array and store it with the game information. So the month of July would look something like this:
if(month == 7) // July
{
var gamesPlayed = ["7/1/16: Team1 # Team2", "7/3/16: Team2 # Team 4",
"7/4/16: Team3 # Team2" , ... ,etc, ...];
}
In my main function (the one that executes when I push the Submit button), I want to print the array.
var schedule = getSchedule(July);
for(var i = 0; i < schedule.length; i++)
{
document.getElementById("result").innerHTML = schedule[i] + "<br />";
}
For some reason this does not work. All it does it print the very last value in the array and not the whole thing. How come it is not printing the whole array? I tried to do document.write(schedule[i] + "<br />"); and that didn't do what I wanted. It printed it, but it printed it on a page by itself to where I couldn't time in a new month or go back to a homepage, etc. Is there a way to get this to print all the elements and not just the last one?
You can use .join() to combine the array into one string, and separate each entry by <br>:
document.getElementById("result").innerHTML =
schedule.join("<br>");
There's no need for the self-closing / in <br>. More important, there's no need for the for loop. That code above will do the whole thing.
If you want a <br> after the last entry, just add it:
document.getElementById("result").innerHTML =
schedule.join("<br>") + "<br>";
While Pointy's answer is correct it does not explain why your code is not working. I'll try and explain:
The error is in this for loop and how you are using innerHTML.
for(var i = 0; i < schedule.length; i++)
{
document.getElementById("result").innerHTML = schedule[i] + "<br />";
}
Basically, on each iteration of the loop you are resetting the HTML of the result element instead of appending to it. The following small change is all that would have been needed.
for(var i = 0; i < schedule.length; i++)
{
document.getElementById("result").innerHTML += schedule[i] + "<br />";
}
However, Pointy's answer is more efficient for sure.

Replace array-mapped variables with the actual variable name/string?

I am trying to edit a Greasemonkey/jQuery script. I can't post the link here.
The code is obfuscated and compressed with minify.
It starts like this:
var _0x21e9 = ["\x67\x65\x74\x4D\x6F\x6E\x74\x68", "\x67\x65\x74\x55\x54\x43\x44\x61\x74\x65", ...
After "decoding" it, I got this:
var _0x21e9=["getMonth","getUTCDate","getFullYear", ...
It is a huge list (500+ ). Then, it has some variables like this:
month = date[_0x21e9[0]](), day = date[_0x21e9[1]](), ...
_0x21e9[0] is getMonth, _0x21e9[1] is getUTCDate, etc.
Is it possible to replace the square brackets with the actual variable name? How?
I have little knowledge in javascript/jQuery and can not "read" the code the way it is right now.
I just want to use some functions from this huge script and remove the others I do not need.
Update: I tried using jsbeautifier.org as suggested here and in the duplicated question but nothing changed, except the "indent".
It did not replace the array variables with the decoded names.
For example:
jsbeautifier still gives: month = date[_0x21e9[0]]().
But I need: month = date["getMonth"]().
None of the online deobfuscators seem to do this, How can I?
Is there a way for me to share the code with someone, at least part of it? I read I can not post pastebin, or similar here. I can not post it the full code here.
Here is another part of the code:
$(_0x21e9[8] + vid)[_0x21e9[18]]();
[8] is "." and [18] is "remove". Manually replacing it gives a strange result.
I haven't seen any online deobfuscator that does this yet, but the principle is simple.
Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value.
For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set):
var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];
var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);
var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);
var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];
window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);
In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...].
The filter process would look like this:
Extract the key name using text processing on the js file. Result: _0xf17f
Extract the string src of the key array. Result:
keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
In javascript, we can then use .replace() to parse the rest of the JS src. Like so:
var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';
var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n"
+ "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n"
+ "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n"
+ "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n"
;
var keyArray = eval (keyArrayStr);
//-- Note that `_0xf17f` is the key name we already determined.
var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;
var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) {
return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';
} );
console.log (deObsTxt);
if you run that code, you get:
var _0x41dcx3 = eval("(" + '{id: 3}' + ")");
var _0x41dcx4 = document["createElement"]("div");
var _0x41dcx5 = _0x41dcx3["id"];
window["console"]["log"](_0x41dcx5);
-- which is a bit easier to read/understand.
I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at:
jsbin.com/hazevo
(Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
#Brock Adams solution is brilliant, but there is a small bug: it doesn't take into account simple quoted vars.
Example:
var _0xbd34 = ["hello ", '"my" world'];
(function($) {
alert(_0xbd34[0] + _0xbd34[1])
});
If you try to decipher this example, it will result on this:
alert("hello " + ""my" world")
To resolve this, just edit the replacedSrc.replace into #Brock code:
replacedSrc = replacedSrc.replace (nameRegex, function (matchStr, p1Str) {
var quote = keyArry[parseInt (p1Str, 10)].indexOf('"')==-1? '"' : "'";
return quote + keyArry[ parseInt (p1Str, 10) ] + quote;
} );
Here you have a patched version.
for (var i = 0; i < _0x21e9.length; i++) {
var funcName = _0x21e9[i];
_0x21e9[funcName] = funcName;
}
this will add all the function names as keys to the array. allowing you to do
date[_0x21e9["getMonth"]]()

Counting the words that search inside a string

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>
You are using a variable that is not declared. Remember that Javascript is case sensitive and the variable b is different than B.
You forget to close the for brackets.
You need to compare the substring with the search pattern.
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.
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>");

Categories

Resources