How to check if a variable has increased (JavaScript) - javascript

I want my code to check if a variable has increased. For example, I have a function that looks for the letter A in a text box, which runs every time a key is pressed. Then it counts the number of A's it has found. Then I want to alert me everytime a new A is written. I thought I could do this easily by just checking if the var numberOfA has increased in an if statement, and if it has to alert me, but I can't figure it out. I have tried using ++ and =/== in my if statement, but it alerts me every single time a letter is typed, instead of only everytime an A has been typed. All help is appreciated, I'm pretty new at this.
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
var numberOfA = sentence.length;
if (numberOfA = numberOfA +1) {
alert(" The letter A has been typed ");
}
}

Several problems.
When you write numberOfA = numberOfA + 1, you actually assign a value to numberOfA. Use a === b if you want to test equality.
Also, if you decide to use numberOfA to store the previous count, then you need to compare that with the current sentence.length value.
As a side note: if you are new, then invest time in learning how to use the debugger (e.g. in the browser dev tools). It will save you a lot of time and help you really understand what is happening.

You can not check numberOfA = numberOfA + 1 in your if statement. You can try this -
var numberOfA = 0;
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
if (sentence.length > numberOfA) {
numberOfA = sentence.length;
alert("The letter A has been typed. In your sentence A has found "+numberOfA+" times.");
}
}

Related

How to swap two numbers using javascript function with one parameter

My Requirement is
I want to display this output when I gave a(0) the output should come 5 and when I gave a(5) the output should come 0.
a(0) = 5
a(5) = 0
like this
Hint:
Using this function
function A(num){}
like this
Please Help me how to do this I'm new in JS
Please give me different kind of solutions its more useful to my career.
function swap (input) {
if( input == 0)
return 5;
return 0;
}
i think there is no description needed
I think I see what you are getting at.
You want to input one variable into a function, and return another variable that is not defined yet. Then you want to define that variable by inputting it into the same function, and get the first input as the output. And so you should end up with 2 outputs.
Now this is technically impossible, because there are undefined variables at play. However, programming is about imagination and I think I have a solution (it's technically a hack but it will work):
var i = 1;
var output1;
var output2;
function swap(input) {
function func1(input) {
output2 = input;
i++;
}
function func2(input) {
output1 = input;
i = 1;
alert(String(output1) + "\n" + String(output2));
}
if (i === 1) {
func1(input);
}
else if (i === 2) {
func2(input);
}
}
while(true) {
swap(prompt("Enter your first input (this will be your second output):"));
swap(prompt("Enter your second input (this will be your first output):"));
}
The swap function goes back and forth between the values 1 and 2 in the variable i. That is how it keeps track of first or second inputs and their exact opposite outputs. The input, or parameter of the swap function is whatever the user types into the prompt boxes. Feel free to make it user-friendly, this is just the dirty code behind it. The reason they are outputted together is because the second input is undefined, and so the machine cannot guess what you were going to input. So first my little program collects all the data and just reverses the order when it is time to output. But to the user who knows nothing about JavaScript and what is going on underneath the hood, this would work perfectly in my opinion.
This should work for any data types inputted, I tested it myself with objects, strings, numbers, and arrays. Hope this helps!!
Shorter alternative to #mtizziani's answer:
let swap = x => !x * 5 // yes this is all
console.log(swap(0));
console.log(swap(5));
We toggle the input, so x is now 1 or 0
We multiple by 5.
Job done.

Arrays are causing me problems

So. Started arrays. Yeah went as well as the loops did. And as a result, I need help.
/*jshint multistr:true */
var text = "Yo yo yo, what's / good fam. My name is / Caleb, my dude.";
var myName = "Caleb"
var hits = []
for(var i = 0; i >= text.length; i++){
if(text[i] === 'C') {
}
for(var j = i; i <= i + myName.length; i++){
}
}
That is the exact code that I have. Now, What it needs to do is search for my name within the confines of the text string. Only problem is that its saying that "It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable." This is a CodeAcademy project. I'm just not understanding. If someone could help me with this, I would really appreciate it.
Thanks!
First of all make sure you have all the semicolons right. Also, add some action in case the loop gets a result!
Also, i don't think you have defined var j, did you?
Finally - if it's asking u to push some values into hits array, then use this push method:
hits.push();
To help u i'd need deeper understanding of the task itself. what did u have to do, what were u starting with?
Edit:
var myName = "Caleb"; // define myName before text so it can be used in text
var text = "Yo yo yo, what's / good fam. My name is / "+myName+", my dude."; // define text and use myName variable between two strings, connected with +
var hits = []; // define hits array
for(var i = 0; i < text.length; i++) { //start loop, make sure second parameter is not infinite or it would crash your browser
if(text[i] === 'C') { // if found i that corresponds with 'C'
var letterLocation = i; // set variable letterLocation with value of 'C' position
hits.push(i); // add the location number to hits array with .push method
};
};
console.log(hits); // display hits array in console
Here's some working code for you, just follow the task and change whatever is necessary - hope it helps.
Generally - i changed the order of variables, so that u can use myName in text, also made the for loop print out the position of letter C and push this value into the hits array. Is that what u meant?

mark a specific word after each space

I'm trying to warning the user if he types a word that is not necessary in a textarea.
its just a little validation for some words.
i reach making something like this:
var words = "hello";
$("textarea").keyup(function(e){
var spliting = $("textarea").val().split(" ");
if(e.keyCode == 32){ // when the user hits space bar
if($.inArray(words, spliting) != -1){
$("span").css("background","red");
}else{
$("span").css("background","green");
}
}
});​
is this the best way of doing this ?
and how can i migrate the variable words as a array, if i need to check more then one word?
Demo
To use an array, you will need to loop over each word in it and loop over each word in the split array. However, you can return on the first match:
var words = ["hello","goodbye"];
$("textarea").keyup(function(e){
var spliting = $("textarea").val().split(" ");
for (var i=0; i<words.length; i++) {
if($.inArray(words[i], spliting) != -1){
$("span").css("background","red");
// break on first match since there is no need to continue looping
// if it is already red.
break;
}else{
$("span").css("background","green");
}
}
});​
I have removed the check for spaces. Even though it makes the function more efficient, you need to be wary of cases when someone goes back to correct spelling and ends up with an invalid word. The way you had it, those cases would never cause the flagged words to be found unless a space was typed later.
It would be advisable to call this function for onchange and blur events as well, since typing is not the only way users enter input into form inputs.
Here is the updated demo
You don't need to .split the input every time a key is pressed, this is a situation where a regular expression is to be preferred:
Check the updated fiddle
To generate the expression based on an array:
var blackList = ['hello','world'];
var expression = new RegExp('\\b(' + blackList.join('|') + ')\\b','i');
$("textarea").keyup(function(e)
{
//if (e.keyCode === 32)
//{in comment after reading the answer posted by Michael Berkowski
if ($(this).val().match(expression))
{
$("span").css("background","red");
return;
}
$("span").css("background","green");
//}
});​

what is the logic for paragraph validation in multiline Textbox using javascript?

i am trying to validate text(Paragraph) in javascript for multiline Textbox.
After giving the text in textbox, the very first Letter should be changed to Capital letter, remaining have to remain as small letters.After full stop the first letter should be in Capital. I need to use textchange event also.
I am new to javascript, and i feel this Proper Case validation is very complex, i am not even getting any logic to start with.. Plz give some idea.
Thanks in advance.
Here's a possible answer, though to reiterate my comment, I don't actually think this is a very useful validation approach. You can see a working version here: http://jsfiddle.net/nrabinowitz/5TSK5/
// regex for a single sentence
var testRE = /^[A-Z][^A-Z]+$/;
var paragraphs = text.split('\n');
var pass, paragraph, sentences, sentence;
for (var x=0; x < paragraphs.length; x++) {
paragraph = paragraphs[x];
pass = true;
if (paragraph) {
sentences = paragraph.split(/\. +/);
for (var y=0; y < sentences.length; y++) {
sentence = sentences[y];
// test sentence for validity
if (sentence && !testRE.exec(sentence)) {
pass = false;
}
}
// pass is now either true or false for paragraph x
}
}
You might want to look for a plugin that already does grammar checking like After The Deadline.
#nrabinowitz is right, I wouldn't try to write a natural language grammar checker in javascript unless your stated goal of "capitalization should only occur after a full stop" is the full extent of what you want to do, you'd be attempting to parse a potentially non-context-free language.

javascript for loop not behaving as expected

I know this is really basic but I am new to Javascript
This is a piece of code from a battleship game I am working on for a class
function displayMyBoats(ship){
for (var i = 0; i<ship.length; i++)
{
alert("ship.length = " + ship.length);
alert("Ship[i]= " + ship[i]);
document.getElementById( "Set_" + ship[i] ).src = fnImageShip;
alert("i = " + i);
}
}
I am testing with a ship array that is 5 elements. Everything works fine until it reaches 5, then all of a sudden it thinks the length of the array is 8.
There is no code to increase the length of ship array, so what would cause it to add to the length of the array?
The alerts are my testing to see what all the values are at.
To give you a hint, try adding an alert whenever your script is either entering or exiting the displayMyBoats(). Suddenly jumping to 8 indicates that it's entering the method a second time, this time with a ship of len 8.
Confirm or deny this theory by adding this alert after your for loop block:
alert('exiting displayMyBoats()');`
Perhaps you see more if you use console.log(ship); instead of alert(); - if you are using Firebug/Console.

Categories

Resources