How to count the letters in a text with Javascript? - javascript

I am currently trying to write a ''web application'' that has a simple text area inside, in which I want the letters of the text written to be pointed out.
For example, if I write:
''How old are you? I am 19 years old''
I need a code to tell me how many 'A's and 'Y's and 'D's (and all letters of the alphabet from 0-26) are used in this sentence when I press a button on a HTML/ CSS page.
Could you please tell me what I must write into my .JS file and what I should write into my .HTML file to do this with a click of a button when something is written in the ?
I hope my explanation was detailed enough. Thanks!
Edit (I'm very sorry for the problems I caused) - What I have done so far looks like this:
HTML:
<link rel="stylesheet" type="text/css" href="theme.css">
<meta charset="utf-8">
<script src="test.js" type="text/javascript"></script>
<div class='header'>
Al.Fa.Be
</div>
<div class='yaz'>
<textarea></textarea>
</div>
<div class='description'>
<a href='http://www.google.com'>Ara</a>
</div>
<div class='description2'>
<input id="clickMe" type="button" value="Hesapla" onclick="doFunction();" />
</div>
CSS:
body{
background:white;
}
selection{
background:#CCC;
}
#clickMe{
background:#CCC;
border:1px solid #333;
}
.header{
font-size:70px;
font-weight:bold;
font-family:Arial;
color:#333;
margin-left:580px;
padding-top:200px;
}
textarea{
width:1210px;
height:40px;
color:black;
margin-top:20px;
margin-left:100px;
padding-left:10px;
padding-top:10px;
font-size:18px;
font-family:Arial;
}
.description{
background:#f2f2f2;
padding:6px;
width:50px;
text-align:center;
border:1px solid #ddd;
font-family:Arial;
margin-left:620px;
margin-top:20px;
font-size:14px;
}
.description a{
color:#555;
text-decoration:none;
}
.description2{
background:#f2f2f2;
padding:6px;
width:60px;
text-align:center;
border:1px solid #ddd;
font-family:Arial;
margin-left:750px;
margin-top:-30px;
font-size:14px;
}
.description2 a{
color:#555;
text-decoration:none;
}
.yaz{
color:white;
}
Javascript:
// Input name. Count number of alphabets a-z
class program                                                         
{
    public static void main(String[] args)
    {
        String name = args[0];
        int count[] = new int[29];
        int i,p;
        int n = name.length();
        name = name.toUpperCase();
        char c;
        for (i=0; i<29; i++)
        {
            count[i] = 0;  
        }
        for (i=0; i<n; i++)
        {
            c = name.charAt(i);
            p = (int) c;
            count[p-65]++;
        }
        for (i=0; i<29 ; i++)
        {
            if (count[i] >0)
            {
                System.out.println((char)(i+65) + " occurs " + count[i] + " times");
            }
        }
    }
}
PS: Please remember that I really suck at this and I need to know how to do this in a specific way.

This is how I would do it.
var count = {};
var msg = "Your message";
for(var i = 0; i < msg.length; i++) {
var c = msg[i];
c = c.toLowerCase();
if(typeof(count[c]) == "undefined") {
count[c]=1;
}
else {
count[c]++;
}
}
If you want, you can check for only letters like this:
if('a'.charCodeAt(0) <= c <= 'z'.charCodeAt(0))
//This is a small letter

Try this:
var str = "How old are you? I am 19 years old";
str = str.toLowerCase();// search is case sensitive
var counta = str.match(/a/g);
var countd = str.match(/d/g);
var county = str.match(/y/g);
alert("a:"+counta.length+" d:"+countd.length+" y:"+county.length);
Fiddle here:

Check out this article: http://davidwalsh.name/javascript-unique-letters-string.
It's just what are you looking for.
Edit:
HTML:
<link rel="stylesheet" type="text/css" href="theme.css">
<meta charset="utf-8">
<script src="test.js" type="text/javascript"></script>
<textarea rows="5" cols="10" id="str" value="Insert the string" />
<input type="button" value="Submit" id="button" />
JS:
document.getElementById('button').onclick = function() {
/* returns the size/length of an object */
Object.size = function(obj) {
var size = 0;
for(key in obj) {
if(obj.hasOwnProperty(key)) size++;
}
return size;
}
//initial vars
var str = document.getElementById('str').val;
var letters = new Object;
//loop, figure it out
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
letters[l] = (isNaN(letters[l]) ? 1 : letters[l] + 1);
}
//output count!
for(key in letters) {
console.log(key + ' :: ' + letters[key]);
}
console.log(Object.size(letters));
}
PS: your "javascript" doesn't look like javascript... It looks like java...

Related

I cant make it so after 5 tries it counts as dead

I keep trying to make it work but it simply won't. Please help.
Btw I want it so that when you die it resets.
<!DOCTYPE html>
<html>
<head>
<style>
html,button{
font-family: monospace, monospace;
width:20%;
padding:0%;
margin:0%;
}
button{
text-align: left;
height:150px;
position:absolute;
background-color:transparent;
border:transparent;
outline:none;
}
div{
position:absolute;
transform:translate(20px,-40px);
}
</style>
<script>
var roll = 0;
function play(){//begin
var rep = Math.floor(Math.random() * 6);
if (rep == 0 && roll !== 6){
roll+=1
document.getElementById("hk").innerHTML = "._______<br>\\(#)----'<br>/ /\\<br>(_(<br>";
setTimeout(4000);
setTimeout(function(){
document.getElementById("hk").innerHTML = ",_______<br>\\(=)----*#<br>/ //<br>(_(<br> DEAD";
}, 500);
}else if (rep !== 0 || roll == 6){
document.getElementById("hk").innerHTML = "._______<br>\\(#)----'<br>/ /\\<br>(_(<br>";
setTimeout(function(){
document.getElementById("hk").innerHTML = ",_______<br>\\(=)----'<br>/ //<br>(_(<br>Click";
}, 500);
var roll = 0;
}
}//end
</script>
</head>
<body>
<h1>Russian<br>Roulette</h1>
<button onClick="play()">
<div id="hk">
,_______<br>
\(=)----'<br>
/ /\<br>
(_(<br>
</div>
</button>
<p>click the gun</p>
</body>
</html>
Please no jquery or anything like it.
The javascript and only the javascript do I need help with.
It doesn't let me post this without adding more text so I am currently adding more text so I can post this.

How do I write a javascript with a for loop that repeats a word?

I'm self taught in javascript but I have been struggling to do this, I want to create a js where it has two functions, one works just for the "for loop". And the second one goes for the buttom which only will ask the user two questions with two prompts, one word, and how many times does the user would like to repeat it.
for example, if the user writes "Hello" in the first prompt and then writes "3" in the second prompt question, the outpur needs to be "HelloHelloHello"
I would really appreciate your help,
this is my html
<!DOCTYPE html>
<html>
<head>
<script src="practice1.js"></script>
<title>Repetition</title>
</head>
<body>
<h1> repetition of words </h1>
<p id="resultLoop"> ----- </p>
<button onclick="askUser()">Do the repetitions</button>
</body>
</html>
If you need to use a for loop, then there are a few ways to do this. One way would be to create an array and push the string they input an n number of times. Then join them together.
Example:
let result = [];
const n = 3;
const stringToRepeat = "hello";
for (let i = 0; i < n; i++) {
result.push(stringToRepeat);
}
result = result.join("");
console.log(result);
Output:
hellohellohello
Another way would be to simply concatenate the strings within each iteration of your for loop. Example:
let result = "";
const n = 3;
const stringToRepeat = "hello";
for (let i = 0; i < n; i++) {
result += stringToRepeat;
}
console.log(result);
Output:
hellohellohello
Although String.prototype.concat() also concatenates strings, they recommend using assignment operators for performance reasons.
If you didn't need to use a for loop, then String.prototype.repeat() does exactly what you want. Although, it is still not compatible with Internet Explorer.
Here's an example of what I mean:
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, allGood; // for reuse on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = function(){
const a = [...arguments];
a.shift().classList.add(...a);
return aC;
}
rC = function(){
const a = [...arguments];
a.shift().classList.remove(...a);
return rC;
}
tC = function(){
const a = [...arguments];
a.shift().classList.toggle(...a);
return tC;
}
allGood = nodeArray=>{
for(let n of nodeArray){
if(!hC(n, 'good')){
return false;
}
}
return true;
}
// small library above - magic below can be put on another page using a load Event (except // end load line)
const rep_text = I('rep_text'), rep_x = I('rep_x'), rep_it = I('rep_it'), out = I('output'), goods = [rep_text, rep_x];
rep_text.oninput = function(){
let f = this.value.trim() === '' ? rC : aC; // remove or add class
f(this, 'good');
}
rep_x.oninput = function(){
let f = this.value.match(/^[1-9][0-9]*$/) ? aC : rC;
f(this, 'good');
}
rep_it.onclick = ()=>{
out.textContent = allGood(goods) ? rep_text.value.repeat(+rep_x.value) : '';
// out.scrollIntoView(); // use this but it's a Stack Overflow issue
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; color:#fff; padding:0; margin:0; outline:none; -moz-user-select:none; -ms-user-select:none; -webkit-user-select:none; user-select:none; overflow:hidden;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#333; padding:5px; overflow:auto;
}
.main *{
font:bold 22px Tahoma, Geneva, sans-serif;
}
label>span{
cursor:pointer; display:inline-block; height:27px; text-shadow:-1px 0 #000,0 1px #000,1px 0 #000,0 -1px #000; float:left;
}
input[type=text],input[type=number]{
width:100%; height:38px; background:#fff; color:#000; border-radius:3px; border:1px solid #c00; padding:5px; margin:3px 0; box-shadow:none; -moz-user-select:text; -ms-user-select:text; -webkit-user-select:text; user-select:text;
}
input[type=button],button{
cursor:pointer; width:100%; background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 28px Tahoma, Geneva, sans-serif; padding:5px; border:1px solid #007; border-radius:10px; margin-top:7px;
}
input.good{
border-color:#0c0;
}
#output{
color:#aaf; margin:5px 10px; text-overflow:ellipsis;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<label><span>Text to Repeat</span><input id='rep_text' type='text' value='' /></label>
<label><span>Times to Repeat</span><input class='good' id='rep_x' type='number' value='1' min='1' /></label>
<input id='rep_it' type='button' value='REPEAT' />
<div id='output'></div>
</div>
</body>
</html>

How to prevent html buttons from moving back and forth when I adjust a range slider

When I adjust this range slider, the coresponding text to the right which indicates the video Playback rate, changes from a single digit (i.e. 1) to multiple digits (i.e 0.95). Everytime I do so it causes the buttons directly to the right of the text to move back and forth. I’m wondering how to prevent this movement from happening? I’ve tried adding some space, padding, margin, etc. between the text and buttons but I can’t seem to make it stop. I would defenitely like to keep all of the objects on the same line. Is there a way for example to make the default number of digits constant? For example when it’s set to 1, could it be 1.00 instead, and when it’s .8 can it be 0.80 isntead? I’m not sure if that would work since the playbackrate atribute seems to require a specific number of digits.
<!DOCTYPE html>
<html>
<head>
<style>
div#videoPlayerBox{ width:550px; background:#000; margin:0px auto;}
div#videoControlsBar{ background: #333; padding:10px; color:#CCC; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
#pbr{ width:40%;}
div#PlaybackRateBox{ margin:left; width:28%; text-align:center; border: solid 3px #000; background:#FFF; padding:0px;}
</style>
<script>
var v,p,c;
function myFunction(){document.getElementById("myForm").reset();}
function setPlaySpeednormal(){ c.innerHTML = 1;v.playbackRate = 1;}
function restartVideo(){v.pause();v.currentTime = 0;v.play();}
window.onload = function() {
v = document.getElementById("myVideo");
p = document.getElementById("pbr");
c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = p.value;
v.playbackRate = p.value;
},false);
};
</script>
</head>
<body>
<div id="videoPlayerBox">
<video id="myVideo" width="100%" poster="https://www.dropbox.com/s/8qbvpxvtedcs5lq/2016-07-30_Milonga%20Triste_Guillermo%20Garcia_Tango%20Atipico_San%20Francisco.jpg?raw=1" controls>
<source src="https://www.dropbox.com/s/5rjbtmantuow8vw/testvideo_hfd.mp4?raw=1"
type='video/mp4'/>
Your browser does not support HTML video.
</video>
<div id="videoControlsBar">
<form id= "myForm">
<input id="pbr" type="range" value="1" min="0.5" max="1.2" step="0.05" class="slider">
<span>Speed <span id="currentPbr">1</span>
<input type="button" value="Reset" onclick="myFunction();setPlaySpeednormal();">
<input type="button" value="Restart" onclick="restartVideo();">
</form>
</div>
</div>
</body>
</html>
Try adding this #currentPbr line to your style block as shown below (the last line). Adjust the width to your liking
<style>
div#videoPlayerBox{ width:550px; background:#000; margin:0px auto;}
div#videoControlsBar{ background: #333; padding:10px; color:#CCC; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
#pbr{ width:40%;}
div#PlaybackRateBox{ margin:left; width:28%; text-align:center; border: solid 3px #000; background:#FFF; padding:0px;}
#currentPbr {display: inline-block; min-width: 80px;}
</style>
Here's a function that might help you:
parseNum = (num) => (num == 1 || num === 0) ? num + '.00' : (String(num).length == 3 ? num + '0' : num)
So, now you can call this function before giving value to c.innerHTML. Thus, instead of c.innerHTML = p.value, You can do:
var v,p,c;
function myFunction(){document.getElementById("myForm").reset();}
function setPlaySpeednormal(){ c.innerHTML = 1;v.playbackRate = 1;}
function restartVideo(){v.pause();v.currentTime = 0;v.play();}
const parseNum = (num) => (num == 1 || num === 0) ? num + '.00' : (String(num).length == 3 ? num + '0' : num)
window.onload = function() {
v = document.getElementById("myVideo");
p = document.getElementById("pbr");
c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = parseNum(p.value);
v.playbackRate = p.value;
},false);
};
Here's a screenshot of the function in action:
PS Be sure not to use this function with every number. It just works for the domain of the volume.

Creating a for loop with the same style

This is what I want 1, 2, 3, 4, 5.
They should all be styled the same.
But when I run my code I only get (5);
Can someone please help?
<p id= "text-1"> this </p>
p#text-1{
color:blue;
font-size:20px;
padding:10px;
width:20px;
height:20px;
background:gold;
text-align:center;
}
function forloop(){
for( x = 0; x<=3; x++){
document.getElementById('text-1').innerHTML = x;
}
}
forloop();
If you're trying to programatically create a list going from 1 to 3, then you can do it like this:
<html>
<head>
<style>
p#text-1{
color:blue;
font-size:20px;
padding:10px;
width:20px;
height:20px;
background:gold;
text-align:center;
}
</style>
<script>
function forloop(){
var MAX = 3;
for( x=1; x<=MAX; x++) {
document.getElementById('text-1').innerHTML += x;
if(x < MAX) {
document.getElementById('text-1').innerHTML += ", ";
}
}
}
</script>
</head>
<body onLoad="forloop()">
<p id= "text-1"></p>
</body>
</html>
Note that just based on what you've said here, it would be simpler to just put the contents you want into the page directly. This answer is based on the assumption that you won't always want a list of exactly 3 numbers.
Note also that your div is not wide enough to contain all 3 numbers. You will need to make sure that your styling is what you want, but that is beyond the scope of this answer.
EDIT: If you want each number in its own box, then it will be changed like so:
<style>
span.numblock {
color:blue;
font-size:20px;
padding:10px;
width:20px;
height:20px;
background:gold;
text-align:center;
}
</style>
and
<script>
function forloop(){
var MAX = 3;
for( x=1; x<=MAX; x++) {
document.getElementById('text-1').innerHTML += "<span class='numblock'>"+x+"</span>";
if(x < MAX) {
document.getElementById('text-1').innerHTML += ", ";
}
}
}
</script>
The onload() was just to get the script to run. You might not need it, depending on the context in which this will exist.

JavaScript for loop not changing link text

I have a nested for loop inside a for loop that is supposed to change the link text to a random number between 1 and 5. The ID of the links are "aX_Y", X and Y being numbers. The links are arranged in a 4x3 square. The problem is that the random numbers for the link text is only displayed for the last row:
<!DOCTYPE html>
<html>
<head>
<title>RISK</title>
<style type="text/css" media="screen">
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;padding:20px;}
.one {background: #7B3B3B;}
.two {background: #547980;}
#status {color: #eee;padding:1px;text-align:center}
.current {border:3px solid #000;}
</style>
<script type="text/javascript" charset="utf-8">
var xTurn = true;
var gameOver = false;
var numMoves = 0;
function newgame()
{
var status = document.getElementById('status');
numMoves = 0;
gameOver = false;
xTurn = true;
status.innerHTML = 'Player One\'s turn';
for(var x = 0; x < 4; x++)
{
for(var y = 0; y < 3; y++)
{
document.getElementById('a' + x + '_' + y).innerHTML = Math.floor(Math.random()*5 + 1);
console.log('a' + x + '_' + y);
}
}
}
function current(selected)
{
var status = document.getElementById('status');
var value = selected.value;
}
//document.getElementById("status").setAttribute("class", "two");
</script>
<meta name="viewport" content="user-scalable=no, width=device-width" />
</head>
<body onload='newgame();'>
<p id="status" class="one">Player One's turn</p>
<br />
<br />
<br />
<br /><br />
<p><input type="button" id="newgame" value="New Game" onclick="newgame();" /></p>
</body>
</html>
Here is a direct link to it:
https://dl.dropbox.com/u/750932/iPhone/risk.html
This change to your CSS fixes the issue:
a:link, a:visited
{
color: #eee;
border:3px solid #ccc;
text-decoration:none;
display:inline-block;
padding:20px;
}
(Tested in Firefox)
Your Javascript code is fine; all of the grid squares are getting populated with random numbers. What I am seeing instead is that each row of links is overlapping the previous row, so the numbers in the previous row are being hidden.
Is the overlapping intentional?
All the random numbers are being generated correctly. The top 2 rows are just hidden due to your CSS rules. You can prove this by making the following CSS change:
Change the line that looks like this:
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;padding:20px;}
to this:
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;}
And voila, it's all working beautifully.
Heh, I'm pretty sure it is working...the other boxes are just overlapped by the ones in front and you can't see them. Firebug shows values inside all the boxes.
a {
display:block;
float:left;
}
br {
clear:both;
}
...though actually those top-level elements shouldn't be restyled like that necessarily, I'd put it all in a <div id="game"></div> and make them .game a and .game br.

Categories

Resources