How complete a string without exceed a determinated limit? - javascript

I have a sequence of 47 numbers, where i must complete with 0 (zeros) to right if lenght is lower that 47.
var numbers = "42297115040000195441160020034520268610000054659";
var numbers_lenght = numbers.length;
if (numbers_lenght < 47)
numbers = numbers.concat("0");
alert(numbers);
But i want know of a way where the complement not exceed to > 47 independent of lenght < 47 is the string.
How make this?

On modern browsers, you can use padEnd here:
The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string.
var numbers = "54321";
const result = numbers.padEnd(47, '0')
console.log(result + ' :: ' + result.length);

You don't want to just concatenate 1 0 you want to add 47 - string_length zeros, right? You can use repeat() for that:
var numbers = "123456789123";
var numbers_length = numbers.length;
if (numbers_length < 47) {
numbers = numbers.concat('0'.repeat(47 - numbers_length))
}
console.log(numbers)
console.log("length: ", numbers.length)

There are several ways. You're on the right track. You are concatenating "0" to pad. What you are missing is the repetition.
There are a few ways to solve this. Since you seem to be learning, I'll start with the brute force approach to make sure you understand how it all works.
var numbers = "42297115040000195441160020034520268610000054659";
while (numbers.length < 47) {
numbers = numbers.concat("0");
}
alert(numbers);
All I did was change your if to while.
That said, there are methods built in to JavaScript which can do this for you.
var numbers = "42297115040000195441160020034520268610000054659";
numbers += "0".repeat(47 - numbers.length);
Even more expressive:
var numbers = "42297115040000195441160020034520268610000054659";
numbers = numbers.padEnd(47, "0");

Seems like you can accomplish what you're trying to do if you just stick your logic inside a while loop:
var number1 = "42297115040000195441160020034520268610000054659";
var number2 = "4229711504000019";
console.log(padString(number1, 47, "0"));
console.log(padString(number2, 47, "0"));
function padString(str, minimumLength, paddingCharacter) {
while (str.length < minimumLength) {
str = str.concat(paddingCharacter);
}
return str;
}

Related

How to convert big number to string value in JavaScript without using any external lib?

Convert the ASCII value sentence to its equivalent string
This is for writing a similar program given above. I tried to convert the input directly to string value for the iteration.
What is happening is, assume the input value is
var num = 23511011501782351112179911801562340161171141148;
When I convert this number to string
num.toString()
I'm getting the result like this:
"2.351101150178235e+46"
There are so many similar questions asked in SOF, but I didn't see any proper answers.
Can someone help me with how to iterate each value in the input?
Thanks in advance.
If I understand you mean correctly, you can replace the code char ch = (char)num; with var ch = String.fromCharCode(num);. Like this:
var result = [];
function asciiToSentence(str, len)
{
var num = 0;
for (var i = 0; i < len; i++) {
// Append the current digit
num = num * 10 + (str[i] - '0');
// If num is within the required range
if (num >= 32 && num <= 122) {
// Convert num to char
var ch = String.fromCharCode(num);
result.push(ch)
// Reset num to 0
num = 0;
}
}
}
var str = "7110110110711510211111471101101107115";
var len = str.length;
asciiToSentence(str, len);
console.log(result.join(''));
Reference: String.fromCharCode()
Explanation:
First, inside the function asciiToSentence, we need 2 parameters str and len (str is a string while len is the length of that string).
Next, we make a temporary num to calculate the number inside the string based on this table: ASCII Printable Characters
We trying to parse one-by-one character to a number and multiply it with 10. Then, we compare it between 32 and 122 (based on the number in the table above).
If the number we have is inside the range, we parse that number to a character using String.fromCharCode function and reset the value num. Otherwise, we continue the loop and increase the value num

Printing floating point values with decimals and not with e-notation in JavaScript

When i print a floating point like 0.0000001 in JavaScript it gives me
1e-7
how can i avoid that and instead print it "normally" ?
You can use this:
var x = 0.00000001;
var toPrint = x.toFixed(7);
This sets toPrint to a string representation of x with 7 digits to the right of the decimal point. To use this, you need to know how many digits of precision you need. You will also need to trim off any trailing 0 digits if you don't want them (say, if x was 0.04).
function noExponent(n){
var data= String(n).split(/[eE]/);
if(data.length== 1) return data[0];
var z= '', sign= +n<0? '-':'',
str= data[0].replace('.', ''),
mag= Number(data[1])+ 1;
if(mag<0){
z= sign + '0.';
while(mag++) z += '0';
return z + str.replace(/^\-/,'');
}
mag -= str.length;
while(mag--) z += '0';
return str + z;
}
I've got a simple solution that appears to be working.
var rx = /^([\d.]+?)e-(\d+)$/;
var floatToString = function(flt) {
var details, num, cnt, fStr = flt.toString();
if (rx.test(fStr)) {
details = rx.exec(fStr);
num = details[1];
cnt = parseInt(details[2], 10);
cnt += (num.replace(/\./g, "").length - 1); // Adjust for longer numbers
return flt.toFixed(cnt);
}
return fStr;
};
floatToString(0.0000001); // returns "0.0000001"
EDIT Updated it to use the toFixed (didn't think about it).
EDIT 2 Updated it so it will display numbers 0.0000000123 properly instead of chopping off and showing "0.00000001".

Adding extra zeros in front of a number using jQuery?

I have file that are uploaded which are formatted like so
MR 1
MR 2
MR 100
MR 200
MR 300
ETC.
What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99
So files are formatted
MR 001
MR 010
MR 076
ETC.
Any help would be great!
Assuming you have those values stored in some strings, try this:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
pad("3", 3); // => "003"
pad("123", 3); // => "123"
pad("1234", 3); // => "1234"
var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"
I have a potential solution which I guess is relevent, I posted about it here:
https://www.facebook.com/antimatterstudios/posts/10150752380719364
basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code
var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);
I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.
then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.
Note: see Update 2 if you are using latest ECMAScript...
Here a solution I liked for its simplicity from an answer to a similar question:
var n = 123
String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5); // returns 00123
UPDATE
As #RWC suggested you can wrap this of course nicely in a generic function like this:
function leftPad(value, length) {
return ('0'.repeat(length) + value).slice(-length);
}
leftPad(123, 5); // returns 00123
And for those who don't like the slice:
function leftPad(value, length) {
value = String(value);
length = length - value.length;
return ('0'.repeat(length) + value)
}
But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.
UPDATE 2
In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.
So with ES6 it became as simple as:
var n = '123';
n.padStart(5, '0'); // returns 00123
Note: #Sahbi is right, make sure you have a string otherwise calling padStart will throw a type error.
So in case the variable is or could be a number you should cast it to a string first:
String(n).padStart(5, '0');
function addLeadingZeros (n, length)
{
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
//addLeadingZeros (1, 3) = "001"
//addLeadingZeros (12, 3) = "012"
//addLeadingZeros (123, 3) = "123"
This is the function that I generally use in my code to prepend zeros to a number or string.
The inputs are the string or number (str), and the desired length of the output (len).
var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}
};
Examples:
PrependZeros('MR 3',3); // MR 003
PrependZeros('MR 23',3); // MR 023
PrependZeros('MR 123',3); // MR 123
PrependZeros('foo bar 23',3); // foo bar 023
If you split on the space, you can add leading zeros using a simple function like:
function addZeros(n) {
return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}
So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.
Or as a regular expression:
function addZeros(s) {
return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}
I'm sure someone can do it with one replace, not two.
Edit - examples
alert(addZeros('MR 3')); // MR 003
alert(addZeros('MR 23')); // MR 023
alert(addZeros('MR 123')); // MR 123
alert(addZeros('foo bar 23')); // foo bar 023
It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.
Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)
function pad(str, new_length) {
('00000000000000000000000000000000000000000000000000' + str).
substr((50 + str.toString().length) - new_length, new_length)
}
I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:
function lpad(n, e, d) {
var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
return o; }
Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.
var str = "43215";
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
str = "0" + str;
}
console.log("After : \n string :"+str+"\n Length :"+str.length);
It worked for me !
To increase the zeroes, update the 'max' variable
Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:
str could be a number or a string.
formatting("hi",3);
function formatting(str,len)
{
return ("000000"+str).slice(-len);
}
Add more zeros if needs large digits
In simple terms we can written as follows,
for(var i=1;i<=31;i++)
i=(i<10) ? '0'+i : i;
//Because most of the time we need this for day, month or amount matters.
Know this is an old post, but here's another short, effective way:
edit: dur. if num isn't string, you'd add:
len -= String(num).length;
else, it's all good
function addLeadingZeros(sNum, len) {
len -= sNum.length;
while (len--) sNum = '0' + sNum;
return sNum;
}
Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.
var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);
By adding 100 to the number, then run a substring function from index 1 to the last position in right.
var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);
console.log(month,day);
you will got this result from the date of 2020-11-3
11,03
I hope the answer is useful

How can I parse a string in Javascript?

I have string looking like this:
01
02
03
99
I'd like to parse these to make them into strings like:
1. 2. 3. 99. etc.
The numbers are a maximum of 2 characters. Also I have to parse some more numbers later in the source string so I would like to learn the substring equivalent in javascript. Can someone give me advice on how I can do. Previously I had been doing it in C# with the following:
int.Parse(RowKey.Substring(0, 2)).ToString() + "."
Thanks
Why, parseInt of course.
// Add 2 until end of string
var originalA = "01020399";
for (var i = 0; i < originalA.length; i += 2)
{
document.write(parseInt(originalA.substr(i, 2), 10) + ". ");
}
// Split on carriage returns
var originalB = "01\n02\n03\n99";
var strArrayB = originalB.split("\n");
for (var i = 0; i < strArrayB.length; i++)
{
document.write(parseInt(strArrayB[i], 10) + ". ");
}
// Replace the leading zero with regular expressions
var originalC = "01\n02\n03\n99";
var strArrayC = originalC.split("\n");
var regExpC = /^0/;
for (var i = 0; i < strArrayC.length; i++)
{
document.write(strArrayC[i].replace(regExpC, "") + ". ");
}
The other notes are that JavaScript is weakly typed, so "a" + 1 returns "a1". Additionally, for substrings you can choose between substring(start, end) and substr(start, length). If you're just trying to pull a single character, "abcdefg"[2] will return "c" (zero-based index, so 2 means the third character). You usually won't have to worry about type-casting when it comes to simple numbers or letters.
http://jsfiddle.net/mbwt4/3/
use parseInt function.
parseInt(09) //this will give you 9
var myString = parseInt("09").toString()+". "+parseInt("08").toString();
string = '01\n02\n03\n99';
array = string.split('\n');
string2 = '';
for (i = 0; i < array.length; i++) {
array[i] = parseInt(array[i]);
string2 += array[i] + '. ';
}
document.write(string2);
var number = parseFloat('0099');
Demo
Substring in JavaScript works like this:
string.substring(from, to);
where from is inclusive and to is exclusive. You can also use slice:
string.slice(from, to)
where from is inclusive and to is exclusive. The difference between slice and substring is with slice you can specify negative numbers. For example, from = -1 indicates the last character. from(-1, -3) would give you the last 2 characters of the string.
With both methods if you don't specify end then you will get all the characters to the end.
Paul
Ii they are always 2 digits how about;
var s = "01020399";
var result = []
for (var i = 0; i < s.length; i+=2)
result.push(parseInt(s.substr(i, 2), 10) + ".")
alert( result[2] ) // 3.
alert( result.join(" ") ) // 1. 2. 3. 99.

Javascript regular expressions problem

I am creating a small Yahtzee game and i have run into some regex problems. I need to verify certain criteria to see if they are met. The fields one to six is very straight forward the problem comes after that. Like trying to create a regex that matches the ladder. The Straight should contain one of the following characters 1-5. It must contain one of each to pass but i can't figure out how to check for it. I was thinking /1{1}2{1}3{1}4{1}5{1}/g; but that only matches if they come in order. How can i check if they don't come in the correct order?
If I understood you right, you want to check if a string contains the numbers from 1 to 5 in random order. If that is correct, then you can use:
var s = '25143';
var valid = s.match(/^[1-5]{5}$/);
for (var i=1; i<=5; i++) {
if (!s.match(i.toString())) valid = false;
}
Or:
var s = '25143';
var valid = s.split('').sort().join('').match(/^12345$/);
Although this definitely can be solved with regular expressions, I find it quite interesting and educative to provide a "pure" solution, based on simple arithmetic. It goes like this:
function yahtzee(comb) {
if(comb.length != 5) return null;
var map = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < comb.length; i++) {
var digit = comb.charCodeAt(i) - 48;
if(digit < 1 || digit > 6) return null;
map[digit - 1]++;
}
var sum = 0, p = 0, seq = 0;
for(var i = 0; i < map.length; i++) {
if(map[i] == 2) sum += 20;
if(map[i] >= 3) sum += map[i];
p = map[i] ? p + 1 : 0;
if(p > seq) seq = p;
}
if(sum == 5) return "Yahtzee";
if(sum == 23) return "Full House";
if(sum == 3) return "Three-Of-A-Kind";
if(sum == 4) return "Four-Of-A-Kind";
if(seq == 5) return "Large Straight";
if(seq == 4) return "Small Straight";
return "Chance";
}
for reference, Yahtzee rules
For simplicity and easiness, I'd go with indexOf.
string.indexOf(searchstring, start)
Loop 1 to 5 like Max but just check indexOf i, break out for any false.
This also will help for the small straight, which is only 4 out of 5 in order(12345 or 23456).
Edit: Woops. 1234, 2345, 3456. Sorry.
You could even have a generic function to check for straights of an arbitrary length, passing in the maximum loop index as well as the string to check.
"12543".split('').sort().join('') == '12345'
With regex:
return /^([1-5])(?!\1)([1-5])(?!\1|\2)([1-5])(?!\1|\2|\3)([1-5])(?!\1|\2|\3|\4)[1-5]$/.test("15243");
(Not that it's recommended...)
A regexp is likely not the best solution for this problem, but for fun:
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5).{5}$/.test("12354")
That matches every string that contains exactly five characters, being the numbers 1-5, with one of each.
(?=.*1) is a positive lookahead, essentially saying "to the very right of here, there should be whatever or nothing followed by 1".
Lookaheads don't "consume" any part of the regexp, so each number check starts off the beginning of the string.
Then there's .{5} to actually consume the five characters, to make sure there's the right number of them.

Categories

Resources