This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a number to the shortest possible character string while retaining uniqueness
I want to count something and I only have a single digit to report the result, so I want to use letters for numbers > 9. E.g.
1 => 1
5 => 5
10 => A
30 => U
55 => u // I may have an off-by-one error here -- you get the idea
>61 => z // 60 will be more than enough, so I'll use z to mean "at least 62"
What's the easiest way to do that using javascript?
Here's one of the many ways to do it:
function num2letter(num) {
if( num > 61) return "z";
if( num < 0) return num;
return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[num];
}
I decided base 36 was good enough:
function oneDigit(n) {
var BASE=36;
if (n >= BASE-1) { n = BASE-1; }
return n.toString(BASE);
}
Another way to do it:
function parse(x)
{
if(x<10)return x;
else if(x<36)return String.fromCharCode(x+55).toUpperCase();
else if(x<62)return String.fromCharCode(x+29).toLowerCase();
else return "z";
}
And this little test:
var res="";
for(var a=-10;a<70;a++)res+=a+" -> "+parse(a)+"\n";
alert(res);
And a fiddle: http://jsfiddle.net/nD59z/4/
And the same way, but with less characters and incomprehensible:
function parse(x)
{
return x<10?x:(x<36?String.fromCharCode(x+55).toUpperCase():(x<62?String.fromCharCode(x+29).toLowerCase():"z"));
}
Related
This question already has answers here:
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 2 years ago.
So the challenge is to increment a string and the exact rules are as follows:
If the string already ends with a number, the number should be
incremented by 1.
If the string does not end with a number. the number 1 should be appended to the new string.
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
I've gotten so close with two different attempts. Both check off certain boxes but neither do both.
function incrementString (strng) {
if (/\d/.test(strng) === true) {
var num = +strng.match(/\d+/g)[0] + 1;
return strng.replace(/[1-9]/g,'') + num;
} else {
return strng + "1";
}
}
This returns the string, keeping the zeros ahead of the incremented number. However on a test like "foobar099" I need to return "foobar100" but get "foobar0100".
function incrementString (strng) {
if (/\d/.test(strng) === true) {
var num = +strng.match(/\d+/g)[0] + 1;
return strng.replace(/\d/g,'') + num;
} else {
return strng + "1";
}
}
This is another close attempt that successfully increments tests like "foobar099" -> "foobar100" but abandons the zeros for tests such as "foobar0042" which becomes "foobar43".
Anyone able to solve this?
Is this what you want?
function incrementString(text) {
return text.replace(/(\d*)$/, (_, t) => (+t + 1).toString().padStart(t.length, 0));
}
console.log(incrementString('foo'));
console.log(incrementString('foobar23'));
console.log(incrementString('foo0042'));
console.log(incrementString('foo9'));
console.log(incrementString('foo099'));
This question already has answers here:
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 4 years ago.
guys.
I'm having some issues with this function
const incrementString = str => {
if (!str.match(/[\d+]$/)){
return str += 1
} else{
return str.replace(/[\d+]$/, ch => new Number(ch) + 1)
}
}
What I'm trying to do with that function is + 1 the number at the end of the string, and if the string doesn't has one, I'll add a 1 at the end.
string expected
"foobar000" "foobar001"
"foo" "foo1"
"foobar025" "foobar026"
I don't know if it's possible to do it with replace and regex, I have in mind a solution with loops, .length, split, etc..., but I want to do it with regex, if it's possible.
Problem: How can I take the number at the end of the string, with the leading zeros, and sum them a 1?
this are some examples of the bad behavior of my function
Expected: 'foobar011', instead got: 'foobar11'
Test Passed: Value == 'foo1'
Expected: 'foobar002', instead got: 'foobar2'
Test Passed: Value == 'foobar100'
Test Passed: Value == 'foobar100'
Test Passed: Value == '1'
Thanks and happy holydays
You could store the length of the numerical string and apply after incrementing the wanted leading zeroes.
function increment(s) {
var [left, right = '0'] = s.split(/(\d*$)/),
length = right.length;
return left + (+right + 1).toString().padStart(length, '0');
}
console.log(['foobar000', 'foo', 'foobar025'].map(increment));
I used all your hints and answers to check different options to solve my problem.
Finally, I solved with the "String of numbers" and the padStart hints.
const incrementString = str => {
if (str.match(/[0-9+]+/g)) {
let numbers = str.replace(/[a-z+]+/g, "")
return str.replace(numbers, (Number(numbers) + 1 + '').padStart(numbers.length, 0))
} else {
return str + 1
}
}
I hope this helps others as it helped to me.
Thanks and happy holydays
This question already has answers here:
Get the absolute value of a number in Javascript
(6 answers)
Closed 7 years ago.
Problem: some numbers are positive some are not. Here is my function to convert negative numbers to positive ones and leave positive numbers untouched. Is there a better way of doing it in JavaScript?
function intAbs(integer) {
if(isNaN(integer)) {
throw 'NaN';
}
if(parseInt(integer, 10) !== integer) {
throw 'Not an integer';
}
n = integer * integer;
var x = 1;
var e = 1;
while(!(e < 0.1 && e > -0.1)) {
x = (n / x + x) / 2;
e = n - x * x;
}
return parseInt(x);
}
Update: I don't think this question is a duplicate. I know how to get the absolute value of an integer without Math.abs(). You can see in this question. I have already accepted the answer which states "Yes, there is a better way" and it's not ambiguous.
Update #2: This question is marked as a duplicate of Get the absolute value of a number in Javascript, but this does not address problem if(is there a better way of calculating abs than exactly this algorithm). I give up.
Yes, there is a better way: Math.abs().
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 9 years ago.
I can't figure out how to solve the following problem.
I have an array of numbers from 1 to 100.
I need to convert them to strings but to a length of 5.
So, for instance:
1 becomes 00001
2 becomes 00002
3 becomes 00003
4 becomes 00004
etc, etc..
It seems so easy but I cannot find a function. The best I found was .toFixed(n) which is the number of decimal points to use.
Here's a very simple padding function:
function padLeft(str, length, paddingCharacter) {
str = '' + str; //Make sure that we convert it to a string if it isn't
while (str.length < length) {
str = paddingCharacter + str; //Pad it
}
return str;
}
padLeft(123, 5, '0'); //00123
This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 9 years ago.
I am using following js function in my asp.net MVC application on click of Ok button to make sure that value entered in the text box is integer but it always returns false;
function isInteger(n) {
return n === +n && n === (n | 0);
}
and here is how I am using it:
if (!isInteger(selectedPhoneValue)) {
$("#dialog-numeric-phonevalidation").dialog('open');
return;
}
Please suggest me how to change this function to allow only positive integer/numberic value without "." and "-"
You can use regular Expresion instead
function isInteger(n) {
return /^[0-9]+$/.test(n);
}
function isInteger(n) {
return $.isNumeric(n) && parseInt(n, 10) > 0;
}
Update:
Then change the if check like so:
//Assuming selectedPhoneValue is not already converted to a number.
//Assuming you want an exact length of 10 for your phone number.
if (isInteger(selectedPhoneValue) && selectedPhoneValue.length == 10) {
$("#dialog-numeric-phonevalidation").dialog('open');
return;
}
You can use this code to strip out the "." and "-" characters.
selectedPhoneValue = selectedPhoneValue.replace(/-/g, "").replace(/\./g, "");