javascript output random line from input - javascript

Is there a way to chose a random line from an input or textarea with a javascript?
Currently I find a few results that seems to be working, but mostly use jquery and other additional languages. I'm looking for Javascript only.
I've seen javascripts that pick a random line from a local file, I know how that works, but is there a way to do it without local file, and just from an input?
Thanks for your help!

Firstly, split your input text by newline characters (that will produce an array of lines). Then take a random element from that array. To achieve this, use Math.random() function which produces a random float between 0 and 1 and then multiply it by lines array length to get a random float between 0 and lines.length. And finally, use Math.floor() to get an integer to be used as an index.
const lines = input.split('\n');
const randomLine = lines[Math.floor(Math.random() * lines.length))];

Related

(solved) Javascript : Cutting/Removing excess characters from a string if it exceeds the Limit

This question is a bit tricky to explain. Say i have an variable whose length is dynamic meaning it is random,i want to change its length to the first 5 or a certain amount of characters regardless of the length of the characters existing in the variable. I hope i could explain what i am trying to do
.________________________________________________________________________.
I really dont know which direction to go in or what step to take in order to reach my goal but i just copy/pasted some random code of the internet that didn't work so i did not think it is of any importance to include in this query,but i could share on demand
Pseudo code...
const str = "the string";
const start = 0;
// const end = str.length;
str.substring(start, (optional) end);
So if you want just first five characters, you do something like
str.substring(0, 5);
If it's only integers (numbers) you could simply generate a random whole number between 11111 and 99999 (so it's always 5 digits), like this:
let x = Math.floor((Math.random() * 99999) + 11111);
do you have a delimited amount of decimals? if not, you should remove Math.floor and convert into string and after that substring as in the other answer (and convert back into a Number if needed as Number). If yes, you should change the "11111" and "99999" to the length of integers needed, and use toFixed() to limit the number of decimals. –
DavidTaubmann

Color hex code does not output using Javascript function [duplicate]

I'm using a canvas library that requires the colors to be declared in hex number format (e.g. 0x0000FF) but I'm using a jQuery plugin for color inputs that receives the colors in string format ("#0000FF").
I'm using color.toString(16) to get the color number as a string - don't worry about the # - but when the color has leading zeros like in the example value I get "ff" and the color input doesn't work properly.
I need it to be "0000ff" but I don't know how to make a generic solution that works for colors with or without leading zeros. What would be the best approach for this?
You can use the String#padStart function to add 0 until your string has a length of 6 characters.
const color = 0x0000FF;
console.log(color.toString(16).padStart(6, '0'));

problem with parsing numbers using JQuery

i have a Javascript file that calculates and parse the rows in a crm module called jobs.
I have function called recalculateSummary that calculate the price like this
I want it to show 3,578.00 in total like Line Total
The problem is the function parseFloat i think it ignores the ',' as i want if i write 3,578.00 the total should be 3,578.00.
I was able to achive this by removing parseFloat function and removing the ReplaceAll function but i got error when i add more rows the total value becomes 0.00.
recalculateSummary: function(){
var subtotal = 0;
$.each($('.row_line_total'), function(index,value){
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
subtotal += parseFloat(lineTotal);
});
i know the question isn't clear but i need some help
Are trying to add toFixed(2) for calculation result?
I mean this:
$('.summary_subtotal').html($.number(subtotal,2));
->
$('.summary_subtotal').html($.number(subtotal.toFixed(2),2));
The reason is that by replacing the comma with the dot, parseFloat will interpret that as the decimal separator and so your number suddenly is a factor of 1000 smaller.
Take for example 3,578.00
Your code will grab that value as a string with $(value).html().
This is OK, although it would be better to do $(value).text() as
you are not really interested in HTML encoding, but plain text.
Then the code performs a disastrous replacement with
.replaceAll(",", "."). This will turn the string to "3.578.00"
(Not good!).
Finally the code converts this string to number with parseFloat.
The first dot is interpreted as decimal separator, not as thousands
separator (which it originally was). The second dot cannot be
interpreted as part of the number, and so parseFloat returns a
number with value 3.578. You probably have some other mechanics in
place to only display 2 decimal digits, so this value ends up on the
page as 3.58 (rounded).
In order to fix this problem, replace this:
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
with:
lineTotal = $(value).text().replace(/[^.\d]/g, '');
Here we remove anything that is neither a dot (.), nor a digit (\d), using a regular expression: [^.\d]. So now the example value will become "3578.00" (the thousands separator is removed). parseFloat will turn this string into the number 3578. Your rendering mechanics will possibly render that with two decimals and a thousand separator as 3,578.00
All in all it is better to write your logic based on numeric variables and only use the DOM elements for output, not to read values from it (which are already formatted).

JavaScript - Taking Input and displaying it to HTML element, as an integer

What I am trying to do is make an EV Track for Pokemon, you do not need to know what that is. Basically I want to add, for example, 3 into the attack input box, and 2 into defense and click submit, then 3 should appear in the grid under attack, and 2 under defense. Then if I put 1 in the attack input box, it should add 1 to the display in the grid.
But right now, instead of adding the numbers like numbers, it treats them as strings, and only adds them to the attack display.
Here is my code
http://pastebin.com/xy8232nG
Sorry if I do something wrong related ot the format of my question, just let me know, I'll fix it
So I added that parseint thing, and it works fine until I change the number or add 2 to attack and 2 to hp or something like that, it gives me "NaN" instead of a number
edit: so only the attack and special attack displays work, and if i input a value into any other stat, the special attack and attack values change to "NaN"
First off, you wrote defD as defF in your code by accident.
But more importantly, you are mixing strings and numbers. In Javascript, innerHTML returns a string. A string can be any piece of text, like "I am a jelly donut". It returns a string because innerHTML is capable of carrying more than numbers - it could contain text too. So innerHTML returns a string, just to be safe.
As such, you are trying to add a number to a string (piece of text) and you can't add a number to a sentence. So Javascript decides to treat the number like another piece of text rather than a number, and simply tacks the second number on the end of the first one rather than doing a mathematical equation.
Now many others have been saying "use parseInt, use parseInt!" and normally, that would work. That is because parseInt is a function that takes strings and converts them to numbers. However, when you start out, some of your textboxes are empty, so parseInt does not know what to do. So you get NaN (or, "Not a Number" to be exact) because the box is blank.
Usually, I avoid using parseInt because it is a function and in general, using plain math works faster and better than using a function in JS. An easy workaround to your problem is to to multiply the strings by one. Now, I know what you're thinking. "But if adding a number to text doesn't work, why does multiplying?" Simple. You cannot multiply text. As such, Javascript is forced to think of it like two numbers, rather than two strings.
atk += document.getElementById('atk').value*1;
spa += document.getElementById('spa').value*1;
def += document.getElementById('def').value*1;
spd += document.getElementById('spd').value*1;
hp += document.getElementById('hp').value*1;
spe += document.getElementById('spe').value*1;
document.getElementById("atkD").innerHTML = atk;
document.getElementById("spaD").innerHTML = spa;
document.getElementById("defD").innerHTML = def;
document.getElementById("spdD").innerHTML = spd;
document.getElementById("hpD").innerHTML = hp;
document.getElementById("speD").innerHTML = spe;
An added bonus is that this won't return NaN like parseInt does. Try it in your code and see.
(Note: you might want to use a for loop to loop through those and shorten your code instead. It isn't really necessary, but it would look nicer in your code.)
Use the parseInt function to make the values integers. Example:
.....
atk += parseInt(document.getElementById('atk').value);
.....

Javascript - extract specific numbers from string

I'm trying to extract specific numbers from a string but I'm not sure how to execute it.
The string is of the form:
center=43.571464,7.129565&zoom=12&size=480x225&markers=color:red%7Clabel:1%7C43.580293713725936,7.115145444335894&markers=color:red%7Clabel:2%7C43.56512073056565,7.121668576660113&sensor=false
The array I want is the marker coordinates near the end, specifically:
[43.580293713725936,7.115145444335894,43.56512073056565,7.121668576660113]
I thought I could pick these number out using their precision (15) but I don't know if that's best. I'm a hack when it comes to using regular expressions. Right now the best I've got is:
str.match(/[-+]?[0-9]*\.?[0-9]+/g)
But that just gives me all of the numbers.
Help much appreciated!
If your string is in str use this regex.
var coordinates = decodeURIComponent(str).match(/([\d.]{10,})/g);
http://jsfiddle.net/CHfcT/
You could try using the following regex
/\d+\.\d{7,}/g
This assumes that:
The marker coordinates always have 7 or more numbers after the dot
No other part of the string contains a similar pattern with more than 7 numbers after a dot
Example (JSFiddle):
str.match(/\d+\.\d{7,}/g);
The reason I picked 7 was because the other numbers in the sample had 6, so that excludes them. If you know that the coordinates always have a fixed number of decimal places, then you could just use that specific number without the , like this:
/\s+\.\d{10}/g

Categories