different value types in javascript alert? - javascript

In strictly native JS, is there a way to display a string and variable in one alert window (or other window)? For now, let's ignore fancy things like jQuery, Vue, Node, etc.
var testNumber = prompt("Enter a number. Let us see how many even numbers
are therein.");
var countEvens = 0;
for (var i = 0; i <= testNumber; i++) {
if (i % 2 === 0){
countEvens++;
}
}
alert("There are " countEvens " even numbers in" testNumber);

Obviously you can. just ad + operator to concatenate. alert("There are " +countEvens +"even numbers in"+testNumber);
var testNumber = prompt("Enter a number. Let us see how many even numbers are therein.");
var countEvens = 0;
for (var i = 0; i <= testNumber; i++) {
if (i % 2 === 0){
countEvens++;
}
}
alert("There are " +countEvens +" even numbers in" +testNumber);

In strictly native JS, there is no alert or any other mechanism for showing output. JS depends on the host environment to provide that sort of API.
A web browser's alert method will pay attention only to the first argument, which it converts to a string if it isn't one already.
If you want to construct your string from multiple variables and literals you can use concatenation:
alert("There are " + countEvens + " even numbers in " + testNumber);
or template strings:
alert(`There are ${countEvens} even numbers in ${testNumber}`);

Related

Javascript - Find opening and closing bracket positions on a string?

I'm making a calculator for a site project of mine where you can type your entire expression before resolving, for example: 2+3*4 would return 14, 22-4 would return 18, 20+5! would return 140, and so on.
And that works for simple expressions like the ones I showed, but when I add brackets the code breaks.
So a simple expression like (2+3)! that should return 120 actually returns 10 or 2+3!.
my original ideia to make even the basic 2+3! work was to separate the string in math simbols and the rest. so it would separate in this case it would separate it into 2, + and 3!; where it would find the symbol and resolve just that part. And that's why it solves 10 instead of not working.
But after trying to solve I couldn't make the code work except in a extremely specific situation, so I decided to redo the code and post this here in case someone could help me out.
This is the function that I'm currently using to prepare my string for evaluation:
function sepOperFat(){
//2+3! it's working
//1+(2-(2+2)+3)! want that to work in the end
var value = document.calculator.ans.value;
var operandoPos = ['0'];
var operandoInPos = [''];
var paraResolver = [];
for(i = 0; i <= value.length; i++){
//check if value[i] is equal to +, -, ×, ÷, * & /
if(value[i] == '+' || value[i] == '-' || value[i] == '×' || value[i] == '÷' || value[i] == '*' || value[i] == '/'){
operandoPos.push(i);
operandoInPos.push(value[i]);
}
}
paraResolver.push(value.slice(operandoPos[0], operandoPos[1]));
for(var total = 1; total <= operandoPos.length; total++){
paraResolver.push(value.slice(operandoPos[total] + 1, operandoPos[total + 1]));
}
document.calculator.ans.value = '';
for(var total = 0; total <= paraResolver.length - 2; total++){
if(paraResolver[total].includes('!')){
document.calculator.ans.value += "factorial(" + paraResolver[total] + ")";
}else{
document.calculator.ans.value += paraResolver[total];
}
document.calculator.ans.value += operandoInPos[total + 1];
}
}
document.calculator.ans.value is the name of the string where i have the expression.
operandoPos is the position on the string where a symbol is at.
operandoInPos is the symbol (I maybe could have used value.charAt(operandoPos) for that too).
paraResolver is the number that I will be solving (like 3).
factorial( is the name of my function responsible for making the number factorial.
the function doesn't have a return because I still want to solve inside the document.calculator.ans.value.
to resolve the equation I'm using document.calculator.ans.value = Function('"use strict"; return '+ document.calculator.ans.value)(); that activates when I press a button.
And yeah, that's it. I just want a function capable of knowing the difference between (2+3)! and 2+(3)! so it can return factorial(2+3) instead of (2+factorial(3)).
Thank you for your help.
Your biggest problem is going to be that order of operations says parentheses need to be evaluated first. This might mean your code has to change considerably to support whatever comes out of your parentheses parsing.
I don't think you want all of that handled for you, but an approach you can take to sorting out the parenthesis part is something like this:
function parseParentheses(input) {
let openParenCount = 0;
let myOpenParenIndex = 0;
let myEndParenIndex = 0;
const result = [];
for (let i = 0; i < input.length; i++) {
if (input[i] === '(') {
if (openParenCount === 0) {
myOpenParenIndex=i;
// checking if anything exists before this set of parentheses
if (i !== myEndParenIndex) {
result.push(input.substring(myEndParenIndex, i));
}
}
openParenCount++;
}
if (input[i] === ')') {
openParenCount--;
if (openParenCount === 0) {
myEndParenIndex=i+1;
// recurse the contents of the parentheses to search for nested ones
result.push(parseParentheses(input.substring(myOpenParenIndex+1, i)));
}
}
}
// capture anything after the last parentheses
if (input.length > myEndParenIndex) {
result.push(input.substring(myEndParenIndex, input.length));
}
return result;
}
// tests
console.log(JSON.stringify(parseParentheses('1!+20'))) // ["1!+20"]
console.log(JSON.stringify(parseParentheses('1-(2+2)!'))) // ["1-",["2+2"],"!"]
console.log(JSON.stringify(parseParentheses('(1-3)*(2+5)'))) // [["1-3"],"*",["2+5"]]
console.log(JSON.stringify(parseParentheses('1+(2-(3+4))'))) // ["1+",["2-",["3+4"]]]
this will wrap your input in an array, and essentially group anything wrapped in brackets into nested arrays.
I can further explain what's happening here, but you're not likely to want this specific code so much as the general idea of how you might approach unwrapping parenthesis.
It's worth noting, the code I've provided is barely functional and has no error handling, and will behave poorly if something like 1 - (2 + 3 or 1 - )2+3( is provided.

How to find total possible values from length and characters?

I'm totally not a Math whiz kid here, but have put together a function with the great help of StackOverflow (and a lot of trial and error) that generates a random serial number from a Formula, group of Letters/Numbers, and array (so as to not duplicate values).
So, my current formula is as follows:
$.extend({
generateSerial: function(formula, chrs, checks) {
var formula = formula && formula != "" ? formula : 'XXX-XXX-XXX-XXX-XXX', // Default Formula to use, should change to what's most commonly used!
chrs = chrs && chrs != "" ? chrs : "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", // Default characters to randomize, if not defined!
len = (formula.match(/X/g) || []).length,
indices = [],
rand;
// Get all "-" char indexes
for(var i=0; i < formula.length; i++) {
if (formula[i] === "-") indices.push(i);
}
do {
rand = Array(len).join().split(',').map(function() {
return chrs.charAt(Math.floor(Math.random() * chrs.length));
}).join('');
// Rebuild string!
if (indices && indices.length > 0)
{
for(var x=0; x < indices.length; x++)
rand = rand.insert(indices[x], '-');
}
} while (checks && $.inArray(rand, checks) !== -1);
return rand;
}
});
Ok, so, what I need to be able to do is to find total possible values and make sure that it is possible to generate a unique serial number before actually doing so.
For example:
var num = $.generateSerial('XX', 'AB', new Array('AB', 'BA', 'AA', 'BB'));
This will cause the code to do an infinite loop, since there are no more possibilties here, other than the ones being excluded from the extension. So this will cause browser to crash. What I need to be able to do here is to be able to get the number of possible unique values here and if it is greater than 0, continue, otherwise, don't continue, maybe an alert for an error would be fine.
Also, keep in mind, could also do this in a loop so as to not repeat serials already generated:
var currSerials = [];
for (var x = 0; x < 5; x++)
{
var output = $.generateSerial('XXX-XXX-XXX', '0123456789', currSerials);
currSerials.push(output);
}
But the important thing here, is how to get total possible unique values from within the generateSerial function itself? We have the length, characters, and exclusions array also in here (checks). This would seem more like a math question, and I'm not expert in Math. Could use some help here.
Thanks guys :)
Here is a jsFiddle of it working nicely because there are more possible choices than 16: http://jsfiddle.net/qpw66bwb/1/
And here is a jsFiddle of the problem I am facing: Just click the "Generate Serials" button to see the problem (it continuously loops, never finishes), it wants to create 16 serials, but 16 possible choices are not even possible with 2 characters and only using A and B characters: http://jsfiddle.net/qpw66bwb/2/
I need to catch the loop here and exit out of it, if it is not able to generate a random number somehow. But how?
The number of possible serials is len * chrs.length, assuming all the characters in chrs are different. The serial contains len characters to fill in randomly, and chrs.length is the number of possible characters in each position of that.

Operator returning incorrect value?

var bedTime = $("bedtime").value;
var wakeUp = $("wakeup").value;
var Value = bedTime < wakeUp;
alert("is " + bedTime + " less than " + wakeUp + '? ' + Value);
My goal here to take user input through an html form (numeric only). This is what I wrote when I started running into the issue. Anything less than 10 except 1 will return the correct value, but anything over is incorrect. For example if bedTime = 10 and wakeUp = 9 it returns true. So just plugging in a few numbers leads me to believe that when comparing variables this way it only compares the first digit? Any workarounds? Thanks guys.
Try using parseInt() or parseFloat() to make sure you are comparing the same type of data.
var Value = parseInt(bedTime) < parseInt(wakeUp);
Comparing strings is different, for example '10' < '9' => true.

Why is my javascript .push method adding too many objects?

I am learning Javascript and have run into an issue with the push method. When I use it within a loop it is making my array 33 items instead of just adding 3 to the list. Initial list is 1-10 items long, user defined. I initiated all the variables in the beginning of the script, and the variable items is only manipulated when the user initially tells me how long the array will be. From there it is basic exercises in array methods, and this is the one that is giving me problems. Following is the push part of the code. I appreciate any feedback and will put more code up if anyone feels it is necessary.
for (i = 0 ; i < 3 ; i++){
newfood = prompt("Please enter food " + (i + 1) + ".");
foods.push(newfood);
}
document.write("<ol>");
i = 0; //resetting variable i to 0
for (i = 0 ; i < items + 3 ; i++){
document.write("<li>" + foods[i] + "</li><br>");
}
document.write("</ol>");
Looks like you're running into string concatenation that's then treating the string as a numeric type. Convert what I assume is a string to an int:
for (i = 0 ; i < parseInt(items) + 3 ; i++) {
document.write("<li>" + foods[i] + "</li><br>");
}

How can I mask an HTML input using javascript?

How can I mask a US phone using javascript on an HTML control.
I would like the input to force the text to be in the following format:
[(111)111-1111]
Here is what I have currently:
mask(str, textbox, loc, delim) {
var locs = loc.split(',');
for (var i = 0; i <= locs.length; i++) {
for (var k = 0; k <= str.length; k++)
{
if (k == locs[i]) {
if (str.substring(k, k + 1) != delim) {
str = str.substring(0,k) + delim + str.substring(k,str.length)
}
}
}
}
textbox.value = str
}
There are three common ways for handling phone number input of a guaranteed format:
1. Accept all numerical input anyway
The likelihood of users with obscure numbers but still living in the US is higher than ever. Accepting all kinds of numerical input alleviates the concern as the number will only be useless if they gave you either not enough numbers or the wrong ones.
2. Split it into three text boxes of fixed lengths
A lot of financial software does this. Not sure why, specifically, but it seems to be rather frequent there. A recommendation is to advance the cursor after keypress to the next box if they've typed the max limit on the textboxes. Also, this guarantees you will get the numbers in whatever format you're expecting, because you can just append the resulting post variables together.
Example of the HTML:
<input id="phonePart1" maxlength="3" name="phonePart1"/>
<input id="phonePart2" maxlength="3" name="phonePart2"/>
<input id="phonePart3" maxlength="4" name="phonePart3"/>
and a little jQuery snippet to merge the three in your format:
var phonePart1 = parseInt($("#phonePart1").val(), 10);
var phonePart2 = parseInt($("#phonePart2").val(), 10);
var phonePart3 = parseInt($("#phonePart3").val(), 10);
var phone = "(";
if (isNaN(phonePart1)||isNaN(phonePart2)||isNan(phonePart3)) {
// Incorrect format
} else {
phone = phone + phonePart1 + ")" + phonePart2 + "-" + phonePart3;
}
3. Use a regular expression to match the number format
You can use a combination of regular expressions to match multiple numbers, or explicitly the one you are asking about. This is probably the technique you're looking for.
This is the regular expression:
/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/
You'd use it like this:
if (yourphonevariable.match(/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/))
{
// it's valid
}
4. If you're looking to format the text itself with a mask...
Consider the jQuery plugin at http://digitalbush.com/projects/masked-input-plugin/. User #John Gietzen suggested this to me outside of this post, so feel free to give him kudos for it.

Categories