Padding a number with leading zeros in JavaScript? - javascript

I'm trying to figure out the sample answer I've found.
Could anyone explain the code below step by step?
The 'str = "0" + str' part is most confusing.
const fillZero = function (n, w) {
let str = String(n);
for (let i = str.length; i < w; i++) {
str = "0" + str;
}
return str;
}
console.log(fillZero(5, 3)); // 005
console.log(fillZero(12, 3)); // 012
console.log(fillZero(123, 3)); // 123

With str = "0" + str he is using string concatenation. For example, if the string was Hello, after that line of code it will be 0Hello.

Usually when using i in the for loop, most people would set i = 0, you are setting it to the length of characters of "n". So as long as n < w (w = 3, according to above), you will be adding 0 + n until n = w.
in the first example: n = 1, w = 3.
str = 0 + 5 after first iteration THEN
str = 0 + 05 after second iteration
i is no longer lesser than 3, so final output is 005.

Related

How can I remove the last emoji of a group of emojis in javascript?

Let's say I have this 3 emojis in a string: πŸ˜€πŸŽƒπŸ‘ͺ
There are not any spaces or any other character except emojis in the string.
How can I remove the last emoji in javascript?
The answer below doesn't use any special package and safely removes the last emoji
function safeEmojiBackspace(str)
{
let initialRealCount = fancyCount(str);
while(str.length > 0 && fancyCount(str) !== initialRealCount - 1)
{
str = str.substring(0,str.length - 1);
}
return str;
}
function fancyCount(str){
const joiner = "\u{200D}";
const split = str.split(joiner);
let count = 0;
for(const s of split){
//removing the variation selectors
const num = Array.from(s.split(/[\ufe00-\ufe0f]/).join("")).length;
count += num;
}
//assuming the joiners are used appropriately
return count / split.length;
}
Sample usage
let str = "somethingπŸ˜€πŸŽƒπŸ‘ͺ";
str = safeEmojiBackspace(str);//"somethingπŸ˜€πŸŽƒ"
You can do this. It will always remove the last emoji.
function removeEmoji() {
var emoStringArray = document.getElementById('emoji').innerHTML;
var lastIndex = emoStringArray.lastIndexOf(" ");
var stripedEmoStringArray = emoStringArray.substring(0, lastIndex);
document.getElementById('emoji').innerHTML = stripedEmoStringArray;
}
<p id="emoji">
πŸ˜€ πŸŽƒ πŸ‘ͺ
</p>
<button onclick="removeEmoji()">Remove</button>
I hope this is what you want.
var emoString = "πŸ˜€ πŸŽƒ πŸ‘ͺ";
emoString = emoString.slice(0, -2);
However, this would work only if you have 3 emojis in total. Hence to achieve a generalised solution, you can use the underscore functions split() and javascript function join() :
var emoString = "πŸ˜€ πŸŽƒ πŸ‘ͺ";
emoString = _.rest(emoString.split(' ')).join(' ')
Hope this will solve your issue.
Ok, here is how I solved it:
function deleteEmoji(emojiStr) {
let emojisArray = emojiStr.match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g);
emojisArray = emojisArray.splice(0, emojisArray.length - 1);
return emojisArray.join("");
}
let emojitext = "πŸ˜€πŸŽƒπŸ‘ͺ";
console.log(deleteEmoji(emojitext));
I was actually surprised that unicode in this day an age is still not fully supported in browsers. I assume a lot of this is down to windows and it's version of UTF-16.
The OP I believe has found his own solution to the original problem, but I thought there has to be a more generic solution to surrogate pair unicode characters.
Anyway, so my solution is convert the text into a UTF-32 array, these can then be manipulated must easier, using slice etc.
After you have done what you want to the array, just convert back.
Below is an example.
Some of the code I got from -> Is it possible to convert a string containing "high" unicode chars to an array consisting of dec values derived from utf-32 ("real") codes?
and http://speakingjs.com/es5/ch24.html
function decodeUnicode(str) {
const r = [];
let i = 0;
while(i < str.length) {
let chr = str.charCodeAt(i++);
if(chr >= 0xD800 && chr <= 0xDBFF) {
var low = str.charCodeAt(i++);
r.push(0x10000 +
((chr - 0xD800) << 10) | (low - 0xDC00));
} else {
r.push(chr);
}
}
return r;
}
function toUTF16(codePoint) {
const TEN_BITS = parseInt('1111111111', 2);
if (codePoint <= 0xFFFF) { return codePoint; }
codePoint -= 0x10000;
const leadingSurrogate = 0xD800 | (codePoint >> 10);
const trailingSurrogate = 0xDC00 | (codePoint & TEN_BITS);
return String.fromCharCode(leadingSurrogate) +
String.fromCharCode(trailingSurrogate);
}
function encodeUnicode(data) {
return data.reduce((a, v) => {
a += toUTF16(v);
return a;
},"");
}
var unicode = decodeUnicode("πŸ˜€πŸŽƒπŸ‘ͺ");
for (let l = 0; l < unicode.length; l ++)
console.log(encodeUnicode(
unicode.slice(0, l ? -l : unicode.length)));
console.log("pick some random ones");
let str = "";
for (let l = 0; l < 20; l ++) {
let rnd = Math.trunc(Math.random()*unicode.length);
str += encodeUnicode(unicode.slice(rnd,rnd+1));
}
console.log(str);

How do I add 1 to a big integer represented as a string in JavaScript?

How do I add 1 to this string in JavaScript?
var message = "12345612345678901234567890";
I want the output like this:
"12345612345678901234567891"
I tried this:
var message = "12345612345678901234567890";
message = parseInt(message);
var result = message + 1;
But parseInt returned a value in scientific notation like 1.234567896453e+25.
Try the big integer library BigInteger.js to add large numbers.
var message = "12345612345678901234567890";
var messageAsNumber = bigInt(message);
var messagePlusOne = messageAsNumber.add('1');
console.log(messagePlusOne.toString());
<script src="https://peterolson.github.io/BigInteger.js/BigInteger.min.js"></script>
There is no need to use libraries (2022), you can just use JS BigInt object
let message = "12345612345678901234567890";
let messageBigInt = BigInt(message);
console.log(messageBigInt + BigInt(1)); // 12345612345678901234567891n
You can create an array from the string in .lengths of 3 beginning from the end of the string.
Use a pattern which checks if adding 1 would result in the index of the array as a number would sum to 1000, if true, increment previous array index by 1 and fill the current array index with "000".
The pattern below only checks and adjusts last two elements of array; the same pattern can be extended to check each index of array, to properly adjust one or more of the indexes to "000" and increment the previous index by 1.
let message1 = "12345612345678901234567890";
let message2 = "12345612345678901234567999";
let message3 = "12345612345678901234999999";
function addNumberToString(str, numToAdd, digits = []) {
const [N, len, max] = [3, str.length, 1000];
for (let i = -N, l = len; digits.length < len / N; i -= N, l -= N) {
digits.unshift(str.slice(i, l));
}
function add(m) {
if (+digits[digits.length - m] + numToAdd < max) {
let n = +digits[digits.length - m];
digits[digits.length - m] = String(Number(n + numToAdd));
} else {
const M = m + 1;
if (+digits[digits.length - M] + numToAdd < max) {
let n = +digits[digits.length - M];
digits[digits.length - M] = String(Number(n + numToAdd));
digits[digits.length - (M - 1)] = "0".repeat(N);
} else {
if (digits[digits.length - (m + 1)]) {
digits[digits.length - (M - 1)] = "0".repeat(N);
add(m + 1);
}
}
}
return digits.join("")
}
return add(1);
}
console.log(
addNumberToString(message1, 1)
, addNumberToString(message2, 1)
, addNumberToString(message3, 1)
);

Count with A, B, C, D instead of 0, 1, 2, 3, ... with JavaScript

This is probably an unusual request, but for my script I need a function that increments by letter instead of number. For example:
This is a numeric example:
var i = 0;
while(condition){
window.write('We are at '+i);
++i;
}
Essentially, I want to count with letters, like Microsoft Excel does, instead of numbers. So instead of printing "We are at 0", "We are at 1", "We are at 2", etc., I need to print "We are at A", "We are at B", "We are at C", etc.
To mimic Excel (the only example I can think of), after reaching index 25 (Z), we could move on to 'AA', 'AB', 'AC', etc.
So it would work great like so:
var i = 0;
while(condition){
window.write('We are at '+toLetter(i));
++i;
}
Even better if somebody can write a function that then converts a letter back into a digit, i.e. toNumber('A') = 0 or toNumber('DC') = 107 (I think).
Thanks!
Here's a simple recursive function to convert the numbers to letters.
It's one-based, so 1 is A, 26 is Z, 27 is AA.
function toLetters(num) {
"use strict";
var mod = num % 26,
pow = num / 26 | 0,
out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z');
return pow ? toLetters(pow) + out : out;
}
Here's a matching function to convert the strings back to numbers:
function fromLetters(str) {
"use strict";
var out = 0, len = str.length, pos = len;
while (--pos > -1) {
out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - 1 - pos);
}
return out;
}
A test: http://jsfiddle.net/St6c9/
Something like this you mean?
function num2chars(num, upper){
num2chars.letters = num2chars.letters || 'abcdefghijklmnopqrstuvwxyz'.split('');
var ret = repeat(num2chars.letters[num%26],Math.floor(num/26));
function repeat(chr,n){
if (n<1) {return chr;}
return new Array(n+1).join(chr);
}
return upper ? ret.toUpperCase() : ret;
}
//usage
while(i<104){
console.log(num2chars((i+=1),true));
}
//=> A..Z, AA..ZZ, AAA..ZZZ
Create an array of letters A, B, C, D, etc. then call A by using array[0] since 0 is the index of A you can use array[i] as the index, just validate so i can't be over 25.
Use either of these ways to create the array:
var alphabet = new Array("A","B","C");
var alphabet = new Array(25);
alphabet[0] = "A";
alphabet[1] = "B";
alphabet[2] = "C";
instead of toLetter(i); use alphabet[i];
Try the following. Tried and tested in few minutes
var prefix = Array('','A','B'); //this will extends to 3x26 letters. Determines the Max generated
//first element of prefix is `''` so you can have A B C D
var prefix = Array('','A','B');
var alphabets = Array('A','B','C','D'); //extend this to Z
var letters = Array();
function fillArray()
{
var prefix_len = prefix.length;
var array_len = prefix_len * alphabets.length;
var alpha_len = alphabets.length;
for(var i=0; i<prefix_len; i++)
{
for(var a=0; a<alpha_len; a++)
letters.push(''+prefix[i]+alphabets[a]);
}
}
function getLetter(index)
{
return letters[index];
}
function generateTestValues()
{
fillArray();
//make sure 10 is less than letters.length
for(var i=0; i<10; i++)
document.write(getLetter(i)+' '); //A B C D AA AB AC AD BA BB BC....
}
HTML
<span id="clickable" onclick="generateTestValues()">Click Me</span>
Thats how you can generate random letters:
function getRandomArbitrary(min, max) {
max = Math.ceil(max);
min = Math.floor(min);
return Math.round(Math.random() * (max - min) + min);
}
function assignLetter(){
var group = ['A', 'B', 'C', 'D'];
var text = 'We are at ';
var str = '';
str = text + group[getRandomArbitrary(0, group.length-1)];
return str;
}
assignLetter();
For future readers I leave what I think is a more straightforward solution:
const aLetterCode = 97
const getLetterFromId = (number) => String.fromCharCode(aLetterCode + number)
console.log('code 0 ->', getLetterFromId(0)) // a
console.log('code 1 ->', getLetterFromId(1)) // b
console.log('code 12 ->', getLetterFromId(12)) // m

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.

Categories

Resources