Started a bootcamp at one of our first tasks is to write a simple program that asks for the users input and logs it to the console.
My code is working but the last subtask isn´t working.
When the browser open the window a pop up shows up with the question what is your name.
You enter your name and it will get logged to the console. If you don´t enter anything the Console logs Hello World!.
All that is working fine, last subtask is to capitalize the first letter of the users input.
I looked up how to do that and found an example with charAt(0) + string.slice(1) and try to used it in my code.
I tried it on every variable that is read but it doesn´t work, what perplexes me the most is that my code still runs and reads your input.
I could really use some help here.
I will of course provide the code.
// Write your JavaScript code here
function getUserName(){
let nameInput = prompt("What is your name?");
return nameInput;
}
function getHelloMessage(){
if(nameInput === ""){
nameInput = "World"
}
return "Hello " + nameInput + " !";
}
function sayHello() {
let messageOutputed = getHelloMessage();
let newMessage = messageOutputed.charAt(0).toUpperCase() + messageOutputed.slice(1);
console.log(messageOutputed);
};
sayHello();
Thanks for your help people.
For capitalizing you can use regex also
and I think this code can help you and solve your problem
// Write your JavaScript code here
function getUserName(){
let nameInput = prompt("What is your name?");
return nameInput;
}
function getHelloMessage(){
let nameInput = getUserName();
if(nameInput === ""){
nameInput = "World"
}
return "Hello " + nameInput + " !";
}
function _capitalizeWord(word) {
return word.charAt(0).toUpperCase() + word.substring(1);
}
function sayHello() {
let messageOutputed = getHelloMessage().match(/[A-Za-z][a-z]*/g) || [];
let newMessage = messageOutputed.map(this._capitalizeWord).join(' ');
console.log(newMessage);
};
sayHello();
If you want output captalize text in console output.
No need to use extra js.
Tested in firefox console and chrome
console.log("%chello world", "text-transform: capitalize;");
Related
I'm having some trouble trying to get multiple checkbox values. It currently is working, just not in the way I wanted/was hoping it would. Right now anything checked is appended to the bottom of the body and not inline with the function it was aiming to be inserted into.
I'm trying to avoid using JQuery or anything except JavaScript as it's all we've currently covered in our class.
function favMedia(media){
var media = document.forms['mediapref']['media'].value;
return media;
}
function pets(pet){
var pet = document.getElementsByName('pets')
for (var checkbox of pet){
if (checkbox.checked)
document.body.append(checkbox.value + ' ');
}
}
function about(text){
var info = document.forms['personal']['about'].value;
return info;
}
function infoForm(media, pet, text){
document.getElementById('infoset').innerHTML = favMedia(media) + "<br>" + pets(pet) + "<br>" + about(text);
}
Is there some way I can assign it just to a single variable to return and then throw into the last function?
Also please give me any tips or improvements on any aspect of the functions if you have any.
Put it in a string that you return from the function.
function pets(pet) {
var pet = document.querySelector('[name="pets":checked');
let selected = [...pet].map(p => p.value);
return selected.join(', ');
}
When I run it shows me the meaning of "Undefined" in Google.
When I run it, it performs a Google search for the word "Undefined".
function search(){
var x = document.getElementById("search").value;
const url = "https://www.google.com/search?q="+ x +"&oq="+ x +"&aqs=chrome..69i57j69i58.1760j0j7&sourceid=chrome&ie=UTF-8";
var win = window.open(url);
}
If the #search field cannot be found document.getElementById() returns undefined, which is used as part of the search query.
You can write a function like this, which will allow you to pass in a value to be searched.
function search(query){
window.open("https://www.google.com/search?q=" + query)
}
Or stick with your code but set a default value in the event that the selector does not return a match
function search(){
let x = document.getElementById("search").value;
if(x){
const url = "https://www.google.com/search?q=" + x
let win = window.open(url);
}
else {
console.log("No elements had the search id")
}
}
I'm trying to return different results for respective google workspace users, the problem I'm facing is... the first answer is returning all users.
E.g. William Tell and John Peter gets the return of Mark Thomas i.e. www.google.com
Expectation: I want to display the answer for respective users.
Where did I go wrong?
function getUserID() {
var user = Session.getActiveUser().getEmail();
var name = AdminDirectory.Users.get(user).name.fullName;
if (name ="Mark Thomas") {
greeting= "www.google.com";
} else if (name ="William Tell"){
greeting = "www.msn.com";
}
} else if (name ="John Peter"){
greeting = "www.yahoo.com";
}
return greeting;
}
Findings:
You need to initialize the variable named greeting on your script.
You have an extra unnecessary closing bracket on the line before else if (name ="John Peter")
statement.
You may test this tweaked script below:
Modified script:
function getUserID() {
var user = Session.getActiveUser().getEmail();
var name = AdminDirectory.Users.get(user).name.fullName;
var greeting; //"greeting" needs to be initialized for the script to work
if(name == "Mark Thomas") {
greeting= "www.google.com";
} else if (name == "William Tell"){
greeting = "www.msn.com";
} else if (name == "John Peter"){
greeting = "www.yahoo.com";
}
return greeting;
}
Test Result:
Suggestion:
Alternatively, I suggest you use a Switch statement since you have multiple fixed conditions instead of a nested If-Else statement. A switch statement is usually more efficient than a set of nested ifs.
Script w/ Switch statement:
function getUserID() {
var user = Session.getActiveUser().getEmail();
var name = AdminDirectory.Users.get(user).name.fullName.toString();
var greeting; //"greeting" needs to be initialized to exist & be used on the script
switch(name){
case name = "Mark Thomas":
greeting = "www.google.com";
break;
case name = "William Tell":
greeting = "www.msn.com";
break;
case name = "Admin IJG": //Added my test account's full name to see if it works
greeting = "www.yahoo.com";
break;
}
return greeting;
}
Sample Test Result:
name ="Mark Thomas" is an assignment not a test for equivalency.
try name == "Mark Thomas"
This chunk of code that I have updates the color of the text but not the actual text...
var lastWordTyped;
var ele = document.querySelector("#my_text");
//code
//...
lastWordTyped = capitalizeFirstLetterOfKeyword(lastWordTyped);
lastWordTyped = lastWordTyped.fontcolor("blue");
ele.innerHTML = lastWordTyped;
function capitalizeFirstLetterOfKeyword(keyword) {
var word;
word = keyword.charAt(0).toUpperCase() + keyword.slice(1);
return word;
}
When I step through it, is recognizing what the new string should be but it doesnt update the actual text to the new string, but it does change its color. Can anybody provide me with the reason as to why it won't update it?
You haven't declared lastWordTyped, so the capitalizeFirstLetterOfKeyword() gets an 'undefined' as input.
Working demo here:
http://jsfiddle.net/yc4mvm1n/1/
var lastWordTyped = "NewWord";
var ele = document.querySelector("#my_text");
lastWordTyped = capitalizeFirstLetterOfKeyword(lastWordTyped);
lastWordTyped = lastWordTyped.fontcolor("blue");
ele.innerHTML = lastWordTyped;
function capitalizeFirstLetterOfKeyword(keyword) {
var word;
word = keyword.charAt(0).toUpperCase() + keyword.slice(1);
return word;
}
Your code looks fine to me.
http://plnkr.co/edit/mRllGWD2bNTxxyWrJENZ?p=preview
Try posting some more code.
function capitalizeFirstLetterOfKeyword(keyword) {
var word;
word = keyword.charAt(0).toUpperCase() + keyword.slice(1);
return word;
}
is returning proper capitalized word back, I am assuming that you are setting values to lastWordTyped somewhere in your //code section
Make sure the element #my_text exists before the JS code is run. You can do this by putting the script at the bottom of the body, or by using
window.onload = function() {
// your code here
}
Super newbie at Javascript here. I have a problem with whitespace that I'm hoping someone can help me with.
I have a function that looks like this:
function createLinks()
{
var i = 0;
tbody = document.getElementsByTagName('tbody')[3];
console.log('test order ID: '+document.getElementsByTagName('tbody')[3].getElementsByTagName('tr')[0].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,''))
trs = tbody.getElementsByTagName('tr');
console.log('trs.length = '+trs.length);
for (i=0;i<trs.length;i++)
{
orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'');
console.log('order: '+orderId);
hrefReturn = 'https://www.example.com/example.html?view=search&range=all&orderId='+orderId+'+&x=13&y=17';
linkReturn = '<a href='+hrefReturn+'>'+orderId+'</a>';
console.log(linkReturn);
trs[i].getElementsByTagName('td')[1].innerHTML = linkReturn;
}
}
I call this function using another function when the page is initially loaded. This works perfectly.
However, I also call this function in another way when data on the page changes. There's a dropdown list that I have an onClick attribute attached to. That onClick event calls the first function, which in turn calls the second function (above). Both of these functions are saved into text variables and appended to the document, as below:
var scriptTextLinks = " function createLinksText() { var i = 0; tbody = document.getElementsByTagName('tbody')[3]; console.log('test order ID: '+document.getElementsByTagName('tbody')[3].getElementsByTagName('tr')[0].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'')); trs = tbody.getElementsByTagName('tr'); console.log('trs.length = '+trs.length); for (i=0;i<trs.length;i++) { orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'').replace(/\s/g,''); orderId = orderId.replace(/\s/g,''); console.log('order: '+orderId); hrefReturn = 'https://www.example.com/example.html?view=search&range=all&orderId='+orderId+'+&x=13&y=17'; linkReturn = '<a href='+hrefReturn+'>'+orderId+'</a>'; console.log(linkReturn); trs[i].getElementsByTagName('td')[1].innerHTML = linkReturn; } console.log('complete'); } "
Finally, here is the specific problem. When THIS version of the same function is called by events on the webpage, it fails to properly delete the whitespace, which breaks the link that it's supposed to create.
This is the exact problem section of code:
orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'').replace(/\s/g,''); orderId = orderId.replace(/\s/g,''); console.log('order: '+orderId);
So instead of storing the variable like it should, like this:
"XXXXXXXXX"
It is stored like this:
"
XXXXXXXXXX
"
Which, again, kills the link.
Can anybody clarify what's going on here, and how I can fix it? Thanks in advance!
To strip all that surrounding whitespace you can use the standard .trim() method.
var myString = " \n XXXXXXX \n ";
myString = myString.trim();
You can strip all leading and trailing, and compress internal whitespace to a single space, as is normally done in HTML rendering, like this...
var myString = " \n XXXX \n YYYY \n ";
myString = myString.replace(/\s+/g, " ").trim();
Also, see tharrison's comment below.
(though my /\s+/g pattern worked fine with the embedded \n newlines)
Cure for IE<9
"shim.js"
(function() {
if (! String.prototype.trim) {
//alert("No 'trim()' method. Adding it.");
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/mg, '');
};
}
})();
(Or, if you might want to do other things in your shim...)
var shim = {
init: function() {
if (! String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/mg, '');
};
}
}
};
shim.init();
Your HTML file
<script type="text/javascript" src="shim.js"></script>