Is this the best way to calculate a string [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I was playing a bit more with html to add to my website, and following this question Dissappear content with html, I now have a phone number box and my javascript code tells me how many characters are in the inputs box, but also includes the spaces. Is there anyway for my javascript to calculate how many characters there are excluding the the spaces?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<input id="id"></input>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var a = document.getElementById("id").value
var str = a
var n = str.length;
if(n==10) {
document.getElementById("demo").innerHTML = "Equal to 10"
}
else {
document.getElementById("demo").innerHTML = "Not equal to 10"
}
}
</script>
</body>
</html>

There's quite a bit that you can and should do to your code (both the HTML and the JavaScript). Some of it will make it more optimized and some of it has to do with the fact that you are using outdated techniques that should be replaced with the modern, standard approach.
See comments inline for details:
<!DOCTYPE html>
<html>
<!-- An HTML document must have a <head> section that
contains a non-empty <title> element. -->
<head>
<title>My Fun Page</title>
</head>
<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<input id="id"> <!-- input elements don't have a closing tag -->
<!-- Don't use HTML event attributes to bind JavaScript callbacks.
Do your event binding in JavaScript -->
<button>Try it</button>
<p id="demo"></p>
<script>
// This is the modern way to bind events:
document.querySelector("button").addEventListener("click", myFunction);
// Just get your element references once, not each time the function runs
const demo = document.getElementById("demo");
const input = document.getElementById("id");
function myFunction() {
// Variables are fine, but they don't help you when you
// are only going to use their value once. In that case
// just refer to what you need:
if(input.value.length == 10) {
// Don't use .innerHTML if you can help it as it has security
// and performance implications. Since you aren't working with
// any HTML anyway here, use .textContent
demo.textContent = "Equal to 10"
} else {
demo.textContent = "Not equal to 10"
}
}
</script>
</body>
</html>

No where in your code do you define "Hello World". Remove the "magic number" 10 (which should be 11, unless spaces and punctuation do not count) and replace it with the desired word length.
Also, use triple-equals (===) for value and type comparison.
const
targetWord = "Hello World",
targetLength = targetWord.length;
function myFunction() {
const str = document.getElementById("id").value;
document.getElementById("demo").textContent = str.length === targetLength
? `Equal to ${targetLength}`
: `Not equal to ${targetLength}`;
}
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<input id="id" value="Hello World" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

This is how I would do it.
The ternary expression is maybe not easy to understand for beginners, but I like them.
<script>
function myFunction() {
const str = document.getElementById("id").value
const message = str.length === 10 ? "Equal to 10" : "Not equal to 10"
document.getElementById("demo").innerHTML = message
}
</script>

Related

Javascript if statement issue: No display in the webpage

I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?
Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.
document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>

How to Title Case a sentence in Javascript

<html>
<head>
<!--Wei Wu Section A-->
<title>This is the 4th extra credit</title>
</head>
<body>
<script type="text/javascript">
function toUpper(stringFromUser){
var arrayOfStrings = [];
arrayOfStrings = stringFromUser.split(" ");
for(i=0;i<arrayOfStrings.length;i++){
//if (char(arrayOfStrings[i][0]) <= 122 && char(arrayOfStrings[i][0]) >= 97){
if (arrayOfStrings[i].charCodeAt(0) <=122 && arrayOfStrings[i].charCodeAt(0) >=97){
arrayOfStrings[i] = arrayOfStrings[i].charAt(0).toUpperCase() + arrayOfStrings[i].slice(1);
}
}
var afterTitle = "";
afterTitle = arrayOfStrings.join(" ");
document.getElementById('afterChange').innerHTML = afterTitle;
}
</script>
<p>Enter a sentence and I will turn it into Title Case!<input id="textInput" value=""></p>
<button onclick="toUpper(textInput.value)">Change case!</button>
<p id="afterChange"></p>
</body>
</html>
Hi thank you in advance for all your help. this is one of the code that I was working on. the purpose of this code is to "Title Case" the first letter of each word in the sentence. My code runs quite well after some work.
But I have one question: On line 14, I was trying to directed assign the uppercase letter to arrayOfString[i][0], it didn't work. Instead, I changed the whole element, AKA the element in the array. Why didn't that work? Thank you very much!
Strings are immutable - you cannot change individual characters in them by assigning to their [] indicies. So, you have to slice them apart and put them back together, as you did.
You can use this code to Title Case
<html>
<head>
<!--Wei Wu Section A-->
<title>This is the 4th extra credit</title>
</head>
<body>
<script type="text/javascript">
function toUpper(stringFromUser){
var afterTitle = toTitleCase(stringFromUser);
document.getElementById('afterChange').innerHTML = afterTitle;
}
function toTitleCase(str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
</script>
<p>Enter a sentence and I will turn it into Title Case!<input id="textInput" value=""></p>
<button onclick="toUpper(textInput.value)">Change case!</button>
<p id="afterChange"></p>
</body>
</html>

innerHTML not printing. (Javascript) [duplicate]

This question already has answers here:
how do I set input from user to the value of an input?
(2 answers)
Closed 6 years ago.
I am not exactly new at coding,
But I am definitely an amateur (especially in Javascript), and I have just started a new project for personal purpose.
I can not seem to get my Javascript to print out my answer, and I do not want to move on with the project until I figure it out, because it is going to have more complicated calculations as I work on it.
My code is as below:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p>Enter Your Macros</p>
<p>Fats</p>
<input type="number" name="fats" id="fatInput"/><br>
<button onclick="myFunction()">Calculate</button><br>
<p id="todaysFat"></p>
<script>
function myFunction() {
var f = document.getElementById("fatInput").innerHTML;
document.getElementById("todaysFat").innerHTML = f;
}
</script>
</body>
</html>
Thank you for all of the help
try;
function myFunction() {
var f = document.getElementById("fatInput").value;
document.getElementById("todaysFat").innerHTML = f;
}
I don't think it's the innerHTML your want but the value of the INPUT.
So that's .value not innerHTML.
eg..
var f = document.getElementById("fatInput").value;
Change the innerhtml to value in the first line.
See the below code:
function myFunction() {
var f = document.getElementById("fatInput").value;
document.getElementById("todaysFat").innerHTML = f;
}
<p>Enter Your Macros</p>
<p>Fats</p>
<input type="number" name="fats" id="fatInput" />
<br>
<button onclick="myFunction()">Calculate</button>
<br>
<p id="todaysFat"></p>

Simple Javascript on html textbox conversion. Doesn't work twice

I'm using the replace method and if I type in "test test" only the first test gets converted to good so it'll become "good test". I'm at a loss on why this is happening. On a side question, if I was to add 20 other words that I would like to replace, would I have to create 20 different str.replace?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "Test" with "Good"</p>
<textarea id="firstbox"></textarea>
<textarea id="secondbox"></textarea>
<button onclick="myFunction()">Change</button>
<script>
function myFunction() {
var str = document.getElementById("firstbox").value.toLowerCase()
var res = str.replace("test", "good");
document.getElementById("secondbox").value = res;
}
</script>
</body>
</html>
Any help would be greatly appreciated
Use regex, change "good" to /good/g
function myFunction() {
var str = document.getElementById("firstbox").value.toLowerCase()
var res = str.replace(/test/g, "good");
document.getElementById("secondbox").value = res;
}
<p>Click the button to replace "Test" with "Good"</p>
<textarea id="firstbox"></textarea>
<textarea id="secondbox"></textarea>
<button onclick="myFunction()">Change</button>

split hindi word maintaining conjuncts using javascript

i am trying out bellow code
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "कसौटी";
var res = str.split("");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
my result should be क, सौ, टी
however it turns out to be क,स,ौ,ट,ी
what exactly can be done to get the above result
is there a way to split hindi character while maintaing the conjuncts
any way in which we split utf -8 encoded characters then merge them back to get above result
please provide details in code , on how exactly it can be done

Categories