How to reverse a mathematical expression saved as a string in JavaScript? - javascript

Suppose a string
var click="2+5-7%8"
is to be reversed to become
"8%7-5+2"
How to do it in Javascript? I am trying to complete the Free Code Camp Calculator Zipline.

It is a simple reverse and join solution.
str.split("").reverse().join("");

function r(s) {
var txt = "";
for(var i = s.length - 1; i >= 0; i--) {
txt += s[i];
}
return txt;
}
var mathex = "2+5-7%8";
alert(r(mathex));

You can try this way :
<html>
<head>
<title>Javascript String Reverse</title>
</head>
<body>
<script>
function strReverse(str){
return str.split('').reverse().join('');
}
var click = "2+5-7%8";
var revClick = strReverse(click);
document.write("click = " + click + "<br>");
document.write("revClick = " + revClick + "<br>");
</script>
</body>
</html>

This article describes three different ways:
* Array.reverse
* Decrementing while-loop
* Recursion
Recursion seems a better approach. That's why I will list it here:
function reverseString(str) {
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString('dwayne');
Hope it helps

Related

How to display image related to an array element whenever the element is mouseovered

I have an arrays of strings (warmUpAll, legsAll) . Then I have a function that randomly picks up few of them (getRandom) and displays them.
I want to display an image somewhere in DOM when the randomly picked elements are mouseovered/clicked. Do you think this could be possible? Should this be added in getRandom function or somewhere else?
here's my getRandom function:
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
if (arr == warmUpAll) {
document.getElementById("warmup").innerHTML = '<span class="exerciseheader">Warm Up - 10 minutes</span>' + "</br>" + result.join(" ");
}
else if (arr == legsAll){
document.getElementById("legsDisplay").innerHTML = '<span class="exerciseheader">Legs</span>' + "</br>" + result.join(" ");
}
}
}
HTML part of this:
<body>
<div id="warmup"></div>
<div id="legsDisplay"></div>
</body>
Thank you guys in advance.
You can write another function for hover or click ex:
function mouseHover()
{
//do something
}
and add it in your function
function getRandom(arr, n) {
//...
if (arr == warmUpAll) {
document.getElementById("warmup").innerHTML = '<span class="exerciseheader" onmouseover="mouseHover()">Warm Up - 10 minutes</span>' + "</br>" + result.join(" ");
}
else if (arr == legsAll){
document.getElementById("legsDisplay").innerHTML = '<span class="exerciseheader" onmouseover="mouseHover()">Legs</span>' + "</br>" + result.join(" ");
}
}
}

Capitalize select option using Javascript

I have a dropdown menu.
I've been trying to capitalize the text inside my select option, but I couldn't make it work.
JS
$.each(responseData.assignments, function(i, v) {
var chapterNum = v.contentLabel;
var assessmentType = v.assessmentType.toLowerCase().replace(/_/g, " ");
var sameAssignmentType = $('#assignment-type-dd option').filter(function(){
return $(this).text() == assessmentType;
})
if(!sameAssignmentType.length){
$('#assignment-type-dd').append('<option value="' + assessmentType + '">' +
assessmentType + '</option>');
}
});
I've tried chaining this code to my assessmentType :
.charAt(0).toUpperCase() + this.slice(1)
But as soon as I do that it give error :
Uncaught TypeError: this.slice is not a function
Can someone please give me a little hint here ? Thanks.
This should work (CSS approach)
#assignment-type-dd option {
text-transform: capitalize;
}
If you need the entire options text to be uppercase use this.
#assignment-type-dd option {
text-transform: uppercase;
}
And if you really hate CSS or you need the Capitalized text to be passed to server or do some other manipulation, use the below JavaScript code
var capitalizeMe = "";
$("#assignment-type-dd option").each(function() {
capitalizeMe = $(this).text();
$(this).text(capitalizeMe.charAt(0).toUpperCase() + capitalizeMe.substring(1));
});
Play it here
Instead of using this.slice(1), try using assessmentType.slice(1).
you need to format it as
string.charAt(0).toUpperCase() + string.slice(1)
One solution could be to use a CSS rule:
select option {
text-transform:capitalize;
}
We can manipulate font setting by CSS alternation also. Try this
<style>
select option {
text-transform:capitalize;
}
</style>
This seems like a problem CSS is best-suited for.
.select {
text-transform: uppercase;
}
You don't need jQuery for this, unless you are trying to capitalize the first letter of each word. In which case a pure JavaScript solution (assuming you are targeting h2 elements) would be:
var a = document.getElementsByTagName('h2');
for (i = 0; i < a.length; i++) {
var words = a[i].innerHTML.split(" ");
for (j = 0; j < words.length; j++) {
if (words[j][0] != "&") {
words[j] = "<span class='first-letter'>" + words[j][0] + "</span>" + words[j].substring(1);
}
}
a[i].innerHTML = words.join(" ");
}
http://jsfiddle.net/ryanpcmcquen/2uLLqy8r/
Otherwise pure css will work: text-transform: capitalize;
https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform
If it is about just showing it then the css text-transform should work.
If you want to do it programatically in Javascript, I suggest creating a function and calling it as needed:
function stringCapitalize(str){
if (str){
str = str.charAt(0).toUpperCase() + str.slice(1);
return str;
}
}
stringCapitalize("moemen"); // returns "Moemen"
If you think that you will use it regularly during this application, then add it to the built-in String.prototype:
String.prototype.stringCapitalize = function () {
if (this){
str = this;
str = str.charAt(0).toUpperCase() + str.slice(1);
return str;
}
}
"moemen".stringCapitalize() // returns "Moemen"
var name = prompt("what is your name");
var firstchar = name.slice(0, 1);
var firstcharuppercase = firstchar.toUpperCase();
var restofName = name.slice(1,name.length);
var capitlisedName = firstcharuppercase + restofName;
alert(" Hello " + capitlisedName);

Taking var with JS prompt - how can I make it through HTML form?

I've been learning HTML/CSS/JavaScript for a couple of weeks now, and I am currently practicing on a mini project, which consists of letting people answer math questions, and validating their answers.
My current progress can be seen at http://dany.faceflow.com
I know I am probably not using the best strategy to develop this mini game, so any advice would be useful on that. However right now, the problem is that I am taking the user answer with a variable through JS prompt, and I want to do it via an HTML form (less annoying).
In my source code you can see this line within the function:
var userInput = prompt(numb1 + symbol + numb2);
Then, still in the same function, I have an if/else structure to compare the user's answer with the right answer. The code works, I just don't know how to make the prompt HTML-based instead. I've tried an html form with an ID and in the JS using getElementById, document.write and some other stuff but I never got it to work for that part.
(Here's all the JS)
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
var userAnswer = function() {
var numb1 = number1();
var numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
// Prompts the user to give an answer. Change this to HTML.
var userInput = prompt(numb1 + symbol + numb2);
//var userInput = document.getElementById('tw').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
return userInput;
}
(The HTML)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="js/script.js"></script>
<title>Improve Your Math Skills!</title>
</head>
<body>
<center>
<button onclick="userAnswer()">PLAY NOW!</button>
<div id="bubble"></div>
<div id="feedback"></div>
<!-- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> -->
</center>
</body>
</html>
Thank you
You can use an input tag instead of the prompt. Change the HTML just as in Dinesh's answer;
<div id="bubble"></div>
<div id="inp" style="display: none;">
<input type="text" id="ans"></input> <button id="subBtn">Submit</button>
</div>
<div id="feedback"></div>
Now, for the JavaScript, there a few things to consider. Firstly, you have
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
Both functions do exactly the same thing; you don't need two separate functions to get two separate random numbers. So, only one function will suffice.
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
Secondly, now we have two functions. userAnswer to post a new question when 'Play Now!' is clicked and, say, evalAnswer to evaluate the answer written in the input field when 'Submit' is clicked.
In userAnswer, you generate two new random numbers and figure out which operation will be conducted on them. At this point, you can simply evaluate the answer yourself and store it in a global variable. This makes things easier when you evaluate the answer, you only need to do a simple comparison.
Other than that, you update innerHTML for bubble and display the div inp.
In evalAnswer, you get the value from ans and compare it with the previously computed value of the current answer, and then accordingly update feedback.innerHTML.
Here's the code;
//variable to maintain the current answer
var curAns = 0;
//Here, I get all the DOMElements I will use
var playBtn = document.getElementById('playBtn');
var bubble = document.getElementById('bubble');
var inp = document.getElementById('inp');
var ans = document.getElementById('ans');
var subBtn = document.getElementById('subBtn');
var feedback = document.getElementById('feedback');
//I add the event listeners
//This is equivalent to using 'onclick'
//in the HTML, and doing it this way is only
//my personal preference
playBtn.addEventListener('click', function() {userAnswer();}, false);
subBtn.addEventListener('click', function() {evalAnswer();}, false);
//Function to get random number
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
//This function will be executed when 'Play Now!' is clicked.
var userAnswer = function() {
//Get two separate random numbers in
//numb1 and numb2
var numb1 = number();
var numb2 = number();
var symbol = '';
var randomSymbol = Math.random();
//Determine the operation to be used
//and compute the corresponding correct answer for the current
//question
if (randomSymbol > 0.5) {
symbol = "+";
curAns = numb1+numb2;
} else {
symbol = "-";
curAns = numb1-numb2;
}
//Add math question to bubble
bubble.innerHTML = 'What is ' + numb1 + ' ' + symbol + ' ' + numb2 + '?';
feedback.innerHTML = '';
//Make inp div visible
inp.style.display = 'block';
//Reset input value to ''
ans.value = '';
};
//This function will be executed when 'Submit' is clicked
var evalAnswer = function() {
//Simply compare input value with computed
//answer and update feedback
if(parseInt(ans.value) !== curAns) {
feedback.innerHTML = 'Wrong answer, try again!';
}
else {
feedback.innerHTML = 'You got it right, congratulations!';
}
};
Here's a working example.
Hope that helped!
What I understand from your question is that you need the same functionality in HTML itself rather than driven by JS in a prompt box, if so,the below additions to your code should help:
HTML adition:
<div id="bubble"></div>
<div id="check_ans_div" style="display:none;">
<input type="text" id="txt_answer" />
<input type="submit" value="Check Answer" onclick="checkanswer()" />
</div>
<div id="feedback"></div>
JS changes:
var number1 = function() {
var numbx = Math.floor(Math.random() * 41) + 10;
return numbx;
}
var number2 = function() {
var numby = Math.floor(Math.random() * 41) + 10;
return numby;
}
var numb1=0; var numb2=0;
var userAnswer = function() {
numb1 = number1();
numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
if(document.getElementById('check_ans_div').style.display=='none')
document.getElementById('check_ans_div').style.display='block';
document.getElementById('txt_answer').value='';
}
function checkanswer(){
var userInput= document.getElementById('txt_answer').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
}

JS - confirmbox inside a function

I have a Javascript who works well, because yesterday i get here some very good solutions.
I want to know if i can extended this Javascript with another Query.
The query now, gives an alert when the number is bigger then 199. It works well.
But now i want to know, if i can get confirmbox inside for the same inputbox, when i write a number bigger then 100?
Here an example
I write the number 110 and i does get an confirm box with an Information(bla bla), and when i click Yes this number stays in the inputbox.
But when i write 200 or bigger then i does get the alert that this number is to big.
Here the code, what i get yesterday, whenn the number is bigger then 199:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page</title>
<script type="text/javascript">
function minMax() {
var min = 0;
var mid = 99;
var max = 199;
var num = parseInt(document.getElementById('value_one').value);
if (num > mid && num < max) {
var r = confirm(num + ' n\'is greater than ' + mid+ '. Press Yes to retain it.');
if (r == false) document.getElementById('value_one').value = "";
return false;
}
if (min > num || max < num) {
alert(num + ' n\'is not between ' + min + ' and ' + max);
return false;
}
</script>
</head>
<body>
<form>
Value: <input type='text' id="value_one" onBlur="minMax();">
</form>
</body>
</html>
Is it possible and if somebody has an idea?
You can use confirm box for this instead of alert. Check the demo it on w3school.
Try this
<script type="text/javascript">
function minMax() {
var min = 0;
var mid = 100;
var max = 199;
var num = parseInt(document.getElementById('value_one').value);
if (num > mid && num < max) {
var r = confirm(num + ' n\'is greater than ' + mid+ '. Press Yes to retain it.');
if (r == false) document.getElementById('value_one').value = "";
return false;
}
if (min > num || max < num) {
alert(num + ' n\'is not between ' + min + ' and ' + max);
return false;
}
}
</script>
Check the demo on jsFiddle.net.
Hope this works out for you.
There is a confirm box you can control it based on the option you selected(yes or cancel).
You can also make the textbox clean when it cross the max (document.getElementById('value_one').value=0)

For-loop changing values to upper or lower case depending on their length

I'm trying to make a simple JavaScript program which prompts you to enter a sentence on page load. This sentence is then split up into an array separated by a space " ".
My issue currently is that it's not converting anything to uppercase or lowercase at all. I can't seem to understand why and some help would be appreciated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>for-loop replacement exercise</title>
<script language="JavaScript" type="text/JavaScript">
var wordString = prompt("Please enter a sentence: ", 0);
var processedString;
var cont = boolean(true);
// this function is called upon page startup
function startMeUp() {
do {
wordString;
if (wordString == "") {
cont = boolean(false);
}
} while(cont);
processString(wordString);
document.write(processedString);
}
// this function is attempting to iterate through a array of strings and anything that is 4 characters long it is put to lower case
// otherwise if the iteration is less than 4 its put to upper case
function processString(someInput) {
var wordArray = someInput.split(" ");
var lengArray = wordArray.length;
for (var i = 0; i < lengArray; i++) {
if (lengArray[i] == 4) {
wordArray[i].toLowerCase();
} else if (lengArray[i] < 4) {
wordArray[i].toUpperCase();
}
}
processedString = wordArray.toString();
}
</script>
</head>
<body onload="startMeUp();">
</body>
</html>
Try assigning the return value to the array index, rather than just calling the function and not storing it:
wordArray[i] = wordArray[i].toLowerCase();
First your not calling startMeUp() so I added that. next you could simplify the code by using a map().
var wordString = prompt("Please enter a sentence: ", '');
startMeUp();
function startMeUp() {
document.write(processString(wordString));
}
function processString(someInput) {
return someInput.split(" ").map(v => {
if (v.length == 4) return v.toLowerCase()
if (v.length < 4) return v.toUpperCase()
return v
}).join(' ')
}

Categories