Javascript Count numbers - javascript

This probably is a very easy solution, but browsing other questions and the internet did not help me any further.
I made a javascript function which will give me a random value from the array with its according points:
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
document.getElementById("Points").innerHTML += punten;
}
I've added a += punten so i can see that it works correctly. It shows me all the point in the div with the id Points.
But what i wanted to do is count it all together so if i were to draw a 4, King and a 10 it should show 24 instead of 41010.
Thanks in advance! And if you're missing any information please let me know

Currently you are just adding strings together, which concatenate (join together) hence why you end up with 41010. You need to grab the current innerHTML (total) and use parseInt() to convert from a string to a number, then add your new cards that have been chosen, then assign this new value to the innerHTML of your element.
Try the following
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
var total = curPoints + parseInt(punten, 10);
document.getElementById("Points").innerHTML = total;
}
More info on parseInt() here
EDIT
I've added this line -
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
Which will try and convert the innerHTML of the "Points" div, but if it is empty (an empty string converts to false) then curPoints will be equal to 0. This should fix the issue of the div being blank at the start.

innerHTML is a string and JavaScript uses + for both string concatenation as numeric addition.
var pointsInHtml = parseInt(document.getElementById("Points").innerHTML, 10);
pointsInHtml += punten;
document.getElementById("Points").innerHTML = punten;
The second parameter 10 of the parseInt method is usually a good idea to keep there to avoid the function to parse it as an octal.
It might be easier to keep a points variable and only at the end put it in the #Points container, that would make the parseInt no longer necessary

innerHTML will be a string, so you need to convert it into an integer prior to adding the card value :)
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1],
curPunten = parseInt(document.getElementById('Points').innerHTML);
document.getElementById("Points").innerHTML = curPunten + punten;
}

Related

Converting time to hexidecimal then to string using javascrit

I am trying to convert present time to hexidecimal then to a regular string variable.
For some reason I can only seem to produce an output in double quotes such as "result" or an object output. I am using Id tags to identify each div which contains different messages. They are being used like this id="somename-hexnumber". The code if sent from the browser to a node.js server and the ID is split up into two words with first section being the person's name then "-" is the split key then the hexidecimal is just the div number so it is easy to find and delete if needed. The code I got so far is small but I am out of ideas now.
var thisRandom = Date.now();
const encodedString = thisRandom.toString(16);
var encoded = JSON.stringify(encodedString);
var tIDs = json.name+'-'+encoded;
var output = $('<div class="container" id="'+tIDs+'" onclick="DelComment(this.id, urank)"><span class="block"><div class="block-text"><p><strong><'+json.name+'></strong> '+json.data+'</p></div></div>');
When a hexidecimal number is produced I want the output to be something like 16FE67A334 and not "16FE67A334" or an object.
Do you want this ?
Demo: https://codepen.io/gmkhussain/pen/QWEdOBW
Code below will convert the time/number value d to hexadecimal.
var thisRandom = Date.now();
function timeToHexFunc(x) {
if ( x < 0) {
x = 0xFFFFFFFF + x + 1;
}
return x.toString(16).toUpperCase();
}
console.log(timeToHexFunc(thisRandom));

How can I display an array in HTML so that numbers are broken into new line

I am trying to display an array in HTML so that the displayed integers are broken into a new line. The JS is breaking them into a new line, yes, but when the numbers are single number like from 0 - 9, they don't break into a new line. The numbers that break into a new line only start from double digit ie. 10 going upwards.
Here is my JS code: I think there is something wrong with the FOR LOOP in the function displayArray, but I just cant figure it out. This is one of the final pieces to almost tie this up!
Thanking you in advance for any contributions!
//Array to hold statistics of number of pages read per sitting over a period of time
const myArray = [];
//Function to calculate number of pages read
let calculate = () => {
var start = document.getElementById("number1").value;
var end = document.getElementById("number2").value;
document.getElementById("number1").value = ""; // make START empty
document.getElementById("number2").value = ""; //make END empty
let totalNumber = end - start;
myArray.push(totalNumber); //Push total number into array
document.getElementById("congrats").textContent =
"Congrats, you read " + totalNumber + " pages today!";//display message
document.getElementById("rightpane").textContent = myArray;//push array into HTML
displayArray();//Call display array
};
//Function to display myARRAY broken down to a new line
const displayArray = ()=> {
let displayedNumbers='';
for (i = 0; i < myArray.length; i++){
displayedNumbers += myArray[i] + "\n";
};
document.getElementById("rightpane").textContent = displayedNumbers;//Append myArray into HTML
}
Append a prefixed 0 to any number less than 10
You could append a number to the start of the list item and increase it by one each time.
I'm not really sure what you are trying to do, but if you want numbers to appear in new line without using lists and CSS you can wrap them in 'pre' tags and it should break it to new row like this:
displayArray();
function displayArray(){
myArray = [0,1,2,3,4];
let displayedNumbers='';
for (i = 0; i < myArray.length; i++){
displayedNumbers += "<pre>"+myArray[i] + "</pre>";
};
document.getElementById("rightpane").innerHTML = displayedNumbers;//Append myArray into HTML
}
#rightpane{
background : #000;
height : 200px;
width: 100px;
color:white;
padding: 5px;
}
<pre>0</pre><pre>1</pre><pre>2</pre><pre>3</pre>
<div id="rightpane"></div>
I have just made your code some corrections...
and adding parseInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
and you also have to look at white-space: pre
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
// Array to hold statistics of number of pages read per sitting over a period of time
const myArray = []
, Num_1 = document.getElementById('number1')
, Num_2 = document.getElementById('number2')
, congrats = document.getElementById("congrats")
, rightpane = document.getElementById("rightpane")
const LeadZeros =(val,lg)=>('0'.repeat(lg)+val).slice(-lg)
// Function to calculate number of pages read
const calculate =_=>
{
let totalNumber = parseInt(Num_2.value) - parseInt(Num_1.value)
Num_1.value = '' // make START empty
Num_2.value = '' // make END empty
myArray.push( LeadZeros(totalNumber,3) ) // Push total number into array
/*
// or:
myArray.push( totalNumber.toString(10).padStart(3, '0') )
*/
congrats.textContent = `Congrats, you read ${totalNumber} pages today!` // display message
rightpane.textContent = myArray.join("\n") // push array into HTML
}
I also remove your function DisplayArray() and use Array.join() method .
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
leadZero function use :
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/repeat
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
leadZero is divided into two parts: (for example lg = 3)
1) '0'.repeat (3) + val ===' 000 '+ val
if val = 5 it gives '0005'
if val = 42 this gives '00042'
nota: the first value is a string and force the setting in value string too
2) () .slice (-lg) <=> () .slice (-3)
when we put a negative value the method string.slice pars the last character and goes up (from 3 here)
the last 3 characters of:
'0005'.slice(-3) => '005'
'00042'.slice(-3) => '042'

Add Javascript to replace Span tags

I have an online store that has limited access to make any correct edits to code.
I am trying to implement proper Price Schema as they have:
<span itemprop="price">$57.00</span>
This is incorrect.
It needs to be set up like this
<span itemprop="priceCurrency" content="USD">$</span>
<span itemprop="price">57.00</span>
Is there something in JavaScript or jQuery that can manipulate this by separating the Currency Symbol and Price?
Thanks
You get the ELEMENT text:
var value = $("span[itemprop='price'").text();
Then you could generate the html using regex like:
var html = '$57.00'.replace(/([^\d])(\d+)/,
function(all, group1, group2){
return 'some html here =' + group1 + '= more hear =' + group2 });
Might not be 100% bug-free, but it should get you started:
<script type="text/javascript">
var n = document.getElementsByTagName('*')
for(var i=0;i<n.length;i++)
{
if(n[i].hasAttribute('itemprop')) //get elements with itemprop attribute
{
var p = n[i].parentNode
var ih = n[i].innerHTML //grab the innerHTML
var num = parseFloat(ih) //get numeric part of the innerHTML - effectively strips out the $-sign
n[i].innerHTML = num
//create new span & insert it before the old one
var new_span = document.createElement('span')
new_span.innerHTML = '$'
new_span.setAttribute('itemprop', 'priceCurrency')
new_span.setAttribute('currency', 'USD')
p.insertBefore(new_span, n[i])
}
}
</script>
Somthing along the lines of
// find all span's with itemprop price
document.querySelectorAll("span[itemprop='price']").forEach(function(sp){
// grab currency (first char)
var currency = sp.innerText.substr(0,1);
// remove first char from price val
sp.innerText = sp.innerText.substr(1);
// create new element (our price-currency span)
var currencySpan = document.createElement("span");
currencySpan.innerText = currency;
currencySpan.setAttribute("itemprop", "priceCurrency");
currencySpan.setAttribute("content", "USD");
// Append it before the old price span
sp.parentNode.insertBefore(currencySpan, sp);
});
Should do what your after.
See demo at: https://jsfiddle.net/dfufq40p/1/ (updated to make effect more obvious)
This should work -- querySelectorAll should be a bit faster, and the regex will work with more than just USD, I believe.
function fixItemPropSpan() {
var n = document.querySelectorAll('[itemprop]');
for (var i = 0; i < n.length; i++) {
var p = n[i].parentNode;
var ih = n[i].innerHTML;
var num = Number(ih.replace(/[^0-9\.]+/g, ""));
n[i].innerHTML = num;
//create new span & insert it before the old one
var new_span = document.createElement('span');
new_span.innerHTML = '$';
new_span.setAttribute('itemprop', 'priceCurrency');
new_span.setAttribute('currency', 'USD');
p.insertBefore(new_span, n[i]);
}
}
Here is a suggestion of how you can make this work, though i would not suggest doing it like this (too many cases for content="").
Example of the logic you could use to transform the incorrect format to the correct one.
Hope you find it useful. :]

generate random string for div id

I want to display YouTube videos on my website, but I need to be able to add a unique id for each video that's going to be shared by users. So I put this together, and I have run into a little problem. I am trying to get the JavaScript to add a random string for the div id, but it's not working, showing the string:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var div = randomString(8);
</script>
<div id='div()'>This text will be replaced</div>
<script type='text/javascript'>
jwplayer('div()').setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
I really like this function:
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
From Create GUID / UUID in JavaScript?
2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.
A simple way to create a unique ID in JavaScript is to use the Date object:
var uniqid = Date.now();
That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.
The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.
var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();
This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.
Here is the reusable function to generate the random IDs :
function revisedRandId() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
// It will not start with the any number digit so it will be supported by CSS3
I think some folks here haven't really focused on your particular question. It looks like the problem you have is in putting the random number in the page and hooking the player up to it. There are a number of ways to do that. The simplest is with a small change to your existing code like this to document.write() the result into the page. I wouldn't normally recommend document.write(), but since your code is already inline and what you were trying do already was to put the div inline, this is the simplest way to do that. At the point where you have the random number, you just use this to put it and the div into the page:
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
and then, you refer to that in the jwplayer set up code like this:
jwplayer(randomId).setup({
And the whole block of code would look like this:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
Another way to do it
I might add here at the end that generating a truly random number just to create a unique div ID is way overkill. You don't need a random number. You just need an ID that won't otherwise exist in the page. Frameworks like YUI have such a function and all they do is have a global variable that gets incremented each time the function is called and then combine that with a unique base string. It can look something like this:
var generateID = (function() {
var globalIdCounter = 0;
return function(baseStr) {
return(baseStr + globalIdCounter++);
}
})();
And, then in practical use, you would do something like this:
var randomId = generateID("myMovieContainer"); // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
i like this simple one:
function randstr(prefix)
{
return Math.random().toString(36).replace('0.',prefix || '');
}
since id should (though not must) start with a letter, i'd use it like this:
let div_id = randstr('youtube_div_');
some example values:
youtube_div_4vvbgs01076
youtube_div_1rofi36hslx
youtube_div_i62wtpptnpo
youtube_div_rl4fc05xahs
youtube_div_jb9bu85go7
youtube_div_etmk8u7a3r9
youtube_div_7jrzty7x4ft
youtube_div_f41t3hxrxy
youtube_div_8822fmp5sc8
youtube_div_bv3a3flv425
I also needed a random id, I went with using base64 encoding:
btoa(Math.random()).substring(0,12)
Pick however many characters you want, the result is usually at least 24 characters.
Based on HTML 4, the id should start from letter:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
So, one of the solutions could be (alphanumeric):
var length = 9;
var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
var id = prefix + Math.random().toString(36).substr(2, length);
Another solution - generate string with letters only:
var length = 9;
var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);
Or you could use Cripto since it's already built in(except in IE11, I swear these guys havent updated in years!)
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples
var id = new Uint32Array(10);
window.crypto.getRandomValues(id);
I also found this:
https://gist.github.com/6174/6062387#gistcomment-3255605
let length = 32;
let id = crypto.randomBytes(length).toString("base64");
There's a lot of ways to do this, but for most people, there's no reason to reinvent the wheel :)
A edited version of #jfriend000 version:
/**
* Generates a random string
*
* #param int length_
* #return string
*/
function randomString(length_) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (typeof length_ !== "number") {
length_ = Math.floor(Math.random() * chars.length_);
}
var str = '';
for (var i = 0; i < length_; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
For generating random ids, you can also use the standard crypto API with its randomUUID() function which is available in node.js (>=v16.7.0) and all relevant browsers except Safari:
const uuid = crypto.randomUUID()
console.log(uuid)
// prints e.g. "7f3f4512-fcf9-45fe-b726-512bba403426"
I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.
<div id="placeholder"></div>
Now, the idea is to dynamically create a new div, with your random id:
var rndId = randomString(8);
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";
this can be apended to your placeholder as follows:
document.getElementById('placeholder').appendChild(div);
You can then use that in your jwplayer code:
jwplayer(rndId).setup(...);
Live example: http://jsfiddle.net/pNYZp/
Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)
May I an share an intuitive way to generate a randomID ?
const getRandomID = (length: number) => {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
Here is an easy one liner:
const generateUniqueID = (idLength) => [...Array(idLength).keys()].map((elem)=>Math.random().toString(36).substr(2, 1)).join("")
Where all you do is enter the idLength and it will return a unique id of that length.
generateUniqueID(23)
>>>'s3y9uebzuo73ih79g0s9p2q' // Id of length 23
First. Assign an id to your div. Like this:
<div id="uniqueid">This text will be replaced</div>
After that, add inside your <script> tag following code:
Document.getElementById("uniqueid").id = randomString(8);
window.btoa(String.fromCharCode(...window.crypto.getRandomValues(new Uint8Array(5))))
Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML5, an ID should start with a letter for compatibility.
function id(prefix = '', length = 7) {
let result = prefix;
for(let i = 0; i < length; i++) {
const random = Math.random();
result += String.fromCharCode(Math.floor(random * 26) + (random < .5 ? 65 : 97));
}
return result;
}
a random number between 0 and 25 is generated then added to either 65 or 97. When added to 65 it will give you an ascii code for a capital letter and when added to 97, an ascii code for a small letter.
Just use built-int crypto.randomUUID() which is supportted by all major browsers:
let uuid = crypto.randomUUID();
console.log(uuid);

Parse HTML source for dollar amounts then set highest amount as var

I need a JavaScript function that will parse the HTML source of the page from which it is called as an external script, retrieve any dollar amounts in the source, and set the highest dollar amount to a JavaScript variable.
So for instance, if the page contains the text, "Your product is $40.32 and tax is $4.50, your total is $44.82.", the JS should parse those values and set $44.82 to "var total" as the highest amount. Possible?
Thanks based on the tips I wrote this, which works. Hopefully yours or my solution will help others:
var dochtml = document.getElementsByTagName('body')[0].innerHTML;
dochtml = dochtml.replace(/(\r\n|\n|\r)/gm,"");
var price_array = new Array;
var pattmatch = /(\$(([0-9]{0,1})?.[0-9]{1,2}))|(\$([1-9]{1}[0-9]{0,2}([,][0-9]{3})*)(.[0-9]{1,2})?)/gi;
price_array = dochtml.match(pattmatch);
if (price_array) {
for (var i=0; itotal || !total) {
var total=price_array[i];
}
}
document.write(total);
}
You can grab the HTML of the current document from the Javascript by grabbing the document's innerHtml, something like:
document.getElementsByTagName('html')[0].innerHTML
Then you can pull out all the currency values with a regular expression, something like:
((\$(([0-9]{0,1})?\.[0-9]{1,2}))|(\$([1-9]{1}[0-9]{0,2}([,][0-9]{3})*)(\.[0-9]{1,2})?))
Just loop through all the matches and every time the current match is greater than the value in total, set total to the current match.
Disclaimer: That regex was pulled from the community on http://gskinner.com/RegExr/ and I can't promise you it's 100% fullproof.
Take a look at this question here, which demonstrates how to extract numbers from a String: Javascript extracting number from string
Try this:
// get all content from page
var content = document.body.innerHTML;
// create an array of all dollar amounts in the content
arrayNum = content.match(/\$[0-9]+\.[0-9]+/g);
// display array of numbers
console.info(arrayNum);
var high = 0;
for(var i = 0; i < arrayNum.length; i++) {
// remove the dollar sign and cast the string to a float
arrayNum[i] = parseFloat(arrayNum[i].substring(1));
// get the high value - O(n) operation
high = ( (arrayNum[i]) > high ) ? arrayNum[i] : high;
}
alert("High value = " high);

Categories