This is for some homework of mine. Javascript has thus so far been the most difficult for me to grasp. Here's a copy of my assignment:
Copy the following code into new file.
<html>>
<body>
<script>
var namIn = window.prompt("Enter Senator’s State and FULL Name, separated by space:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write(namAr + "<br /> Length:" + namArLen);
</script> </body>
</html>
When you execute this code you will see that after you entered your name it was loaded into namAr array. Your output will look like this:
C,o,l,o,r,a,d,o, ,M,a,r,k, ,U,d,a,l,l
Length: 19
Your task:
Add a small iteration that will display your name in reverse order. For example if senator’s state and name as I entered as:
Colorado Mark Udall
your output will be
C,o,l,o,r,a,d,o, ,M,a,r,k, ,U,d,a,l,l
Length: 19
lladU kraM odaroloC
I'm trying to achieve the bold part. They check our coding. I'm not looking for an answer as much as I am a sort of walkthrough or explaination. Anything help, thanks!
RESOLVED
Figured it out, thanks! All great answers- you guys are so smart!
<html>
<body>
<script>
var namIn = window.prompt("Enter Senator’s State and FULL Name, separated by space:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write(namAr + "<br /> Length:" + namArLen);
var i;
for (i = namArLen-1; i >=0;i--)
{
var result = document.write(namAr[i]);
}
</script>
</body> </html>
you can use loop
Instead of
var namAr = namIn.split("");
try
var namAr = namIn.split("").reverse();
Related
I have a project where we have a compare the original code and code written by the user. The user can code and then on button click we have to compare the written code with original code.
I have both original and new code in string
originalHtml : <html><body style='color:white;background:purple;'></body></html>
newHtml : <html> <body style="background:purple;color:white;"> </body> . </html>
Here there are 3 things to keep in mind
1) White space (should not show the difference for white space)
2) ' and " (should not compare quotes, both are valid in HTML)
3) Attribute order (should show difference only for missing attribute, ignore attributes order)
Any suggestions or alternative solution will be appreciated.
I have created a code pen for you, this will solve your problem.
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code');
const btn = document.getElementById('checkcode');
const result = document.getElementById('result');
let originalHTML = `<html><head>
<title>Hello </title>
</head><body>
<p class="hello"></p>
</body>
</html>`
btn.addEventListener('click', checkCode);
function checkCode() {
let newHTMLCode = textArea.value.replace(/\s/g,"");
let oldHTMLCode = originalHTML.replace(/\s/g,"");
if(newHTMLCode === oldHTMLCode) {
console.log(true);
result.innerHTML = 'TRUE';
} else {
console.log(false);
result.innerHTML = 'FALSE';
}
}
<textarea id="code">
</textarea>
</br>
<button id="checkcode">Check Code</button>
<p id="result"></p>
You can convert all of them to one uniform and compare them.
Example:
remove all space, tab (with one space)
replace all ' to "
sort attribute.
and some rule you defined
Example cheerio to get attribute:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);
I have a link to add event to google calendar which is populated from a database, but the date is formatted yyyy-mm-dd, and the time hh:mm, and i cannot alter this, but google calendar will not accept.
Can anyone please help me use javascript and the 'replace' function to remove the'-' and ':' from the html please?
<a href="http://www.google.com/calendar/event?
action=TEMPLATE
&text=Tester12
&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z
&details=Oranges
&location=Newquay
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>
many thanks.
Fetch the href link from tag and store it in a variable.
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Tester12&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z&details=Oranges&location=Newquay&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
This will remove all the '-' and ':' from dates parameter string and will store that link in 'finalLink' var.
Hope it helps.
I have been on the sniff for the whole code solution, and witha bit of mix and match, came up with this, AND IT SEEMS TO WORK!!!!!! But please feel free to edit into perfection!
<script>
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Example Event&dates=2018-12-16T10:3500Z/2018-12-16T12:0000Z&details=Trip to town&location=No mans land&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
</script>
Add Event
<script>
(function() {
Array.prototype.forEach.call(document.querySelectorAll("a.finalLink"), function(link) {
link.href = finalLink;
});
})();
</script>
So, I use this code
<script type="text/javascript">
var urls = new Array();
urls[0] = "/truth";
urls[1] = "/truth1";
urls[2] = "truth2";
var random = Math.floor(Math.random()*urls.length);
window.location = urls[random];
</script>
and I use "/truth1" "/truth2" "dare1" etc
Is it at all possible to have javascript automatically put a random number at the end of the URL between what I set it to?
In other words
I want Javascript to add a number to the end of
truthordare0.weebly.com/truth
truthordare0.weebly.com/dare
To truthordare0.weebly.com/dare1, truthordare0.weebly.com/dare2
To truthordare0.weebly.com/truth1, truthordare0.weebly.com/truth2
putting a random number between 1-25 at the end of "truth" or "dare". If I have to make the numbers two-digit, please let me know!
It might be handy to know:
-The code above will be used on truthordare0.weebly.com/truth
(which will redirect to /truth1, /truth2, etc
-The code above is used in vitemulti.weebly.com/yesorno-select
Thank you very much!!
<script type="text/javascript">
var urls = new Array();
urls[0] = "/truth";
urls[1] = "/truth1";
urls[2] = "truth2";
var random = Math.floor(Math.random()*urls.length);
window.location = "https://truthordare0.weebly.com/" + urls[random];
</script>
I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>
This is a really stupid question.
I have a javascript string variable for a name, and i want to display it where it says user like this:
"Hello, user!" --> "Hello, Chris!
Surely you could have found this answer out easily yourself :p
Put the name in a span and give it an ID
Hello <span id="name"></span>
Then set the text using getElementByID
var name = "Chris";
document.getElementById('name').innerHTML = name;
var user_name = 'Chris';
document.writeln("Hello, " + user_name);
I think document.write plus some string concatenation are what you're looking for:
var user = "Chris";
document.write("Hello, " + user + "!");
Something like this will do the trick.
var user = 'Steve';
document.write('hello ' + user);
If you need to target an element, you can use the usual methods, such as:
var user = 'Steve';
var thisOne = document.getElementById('thisOne');
thisOne.innerHTML = ('hello ' + user);
May as well throw in a jsfiddle so you can play around an experiment.
This is example of dislay string into span tag.
'+' operator uses for string concatenation.
<html>
<head>
<script>
var name = 'Chris';
var field = document.getElementById('show_string');
field.innerHTML( '"Hello, '+ name + '!"' );
</script>
</head>
<body>
<span id='show_string'></span>
</body>
</html>
You can concatenate the user's name with the rest of the string you want to display like so:
<p id="hello"></p>
<script type='text/javascript'>
var user_name = "Chris";
var hello_string = "Hello, " + user_name;
document.getElementById("hello").innerHTML = hello_string;
</script>