Wrap each digitand prepend zeros up to X digits - javascript

Is there a possibility to wrap each character in Javascript and prepend zero's if its less then X digits?
What i get/have:
var votes = 2;
//or
var votes = 123;
//or
var votes = 4321;
what it should to look like:
<span>0</span><span>0</span><span>0</span><span>2</span>
//or
<span>0</span><span>1</span><span>2</span><span>3</span>
//or
<span>4</span><span>3</span><span>2</span><span>1</span>
so the result should be a number with four digits.

here's a tricky version:
var votes = 123;
("0000" + votes).slice(-4); /* 0123 */
thus, to wrap each digit in a <span> you could fetch each digit with $.map and wrap it into its own element, like in this example fiddle: http://jsfiddle.net/cZAWj/
var votes = 973;
$.map(("0000" + votes).slice(-4), function(digit) {
$('<span/>', { text : digit }).appendTo($('body'));
});

Firstly, make it look like a string and pad it...
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Then you can iterate over it and add a span around each number. Then write the markup out as the .html of the parent element.

Well one way to do it would be to convert the number to a string and pre-append 0 until we reach the desired length.
So if you want X digits:
var strNb = "" + nb;
while (strNb.length < X){
strNb = "0" + strNb
}

function formatNumber(d, x) {
var l = String(d).length;
return (l<x?(Array(x-l).join('0') + d):String(d)).replace(/\d/g,"<span>$&</span>");
}

Related

How to increment a string in JavaScript containing leading zeros?

I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));

Output numbers with comma after 3 digits

i have used this jQuery code
jQuery.fn.digits = function(){
return this.each(function(){
jQuery(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
}
for number 150000
and i want it to out put like 150,000
but it is outputting this : 150,000.00
i don't want these extra .00
I find a for loop is easier to understand than a regex.
function addCommas(num) {
var characters = parseInt(num, 10).toString();
var output = '';
for (var offset = characters.length; offset > 0; offset -= 3) {
output = characters.slice(Math.max(offset - 3, 0), offset) + (output ? ',' + output : '');
}
return output;
}
You can use the JQuery Number Formatter plugin, so you do not have to deal with such regular expressions to format your number:
Jquery Number Formatter
Another work around would be to just trim the last 3 characters with
$(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,").slice(0,-3)
Try Math.round before your regex then substring after - this is untested
var newnumber = Math.round(parseInt($(this).text());
var withcommas = newnumber.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
$(this).text(withcommas.substring(0, s.indexOf('.')));

Increment numbers at end of alphanumeric string in JavaScript

I have alphanumeric strings that will always end in a number, but which may have other numbers embedded early on.
I need to increment the numeric ending and return new ID numbers.
Example:
A48-DBD7-398
Which will be incremented in a loop:
A48-DBD7-398
A48-DBD7-399
A48-DBD7-400
How do I separate out the numeric tail from the rest of the string, and then save the two parts into different variables?
I found several other S.O. questions that split numbers out of a string, but they cannot handle mixed alphanumeric characters in the first part -- or else they split out ALL the numbers, regardless where they are. I need to get only the trailing digits.
Update
I found a case where my solution does not work:
ABC123-DE45-1
Duplicates as:
ABC2
ABC3
ABC4
JS Fiddle demo
If you are interested in a different approach you could do something like this:
$('button').click(function () {
var value = $('#in').val(); // get value
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function (match, n) {
return ++n; // parse to int and increment number
}); // replace using pattern
$('#result')[0].innerHTML += '<br>' + value;
}
});
My 2 cents: use regex to identify the pattern and increment the last part.
function incrementAlphanumeric(str) {
const numPart = str.match(/(0?[1-9])+$|0?([1-9]+?0+)$/)[0];
const strPart = str.slice(0, str.indexOf(numPart));
const isLastIndexNine = numPart.match(/9$/);
// If we have a leading zero (e.g. - 'L100A099')
// or there is no prefix - we should just increment the number
if (isLastIndexNine || strPart != null) {
return strPart + numPart.replace(/\d+$/, (n) => ++n );
}
// Increment the number and add the missing zero
else {
return strPart + '0' + numPart.replace(/\d+$/, (n) => ++n );
}
}
works with the following formats for example:
TEST01A06
TEST-100-A100
TEST0001B-101
TEST001A100
TEST001A91
TEST1101
TEST1010
1010
Demo Repl - https://repl.it/#EdoMagen/Increment-alphanumeric-string
Here is another solution, in case it helps
$('button').click(function() {
var ser = $('#in').val();
var arr = ser.split("-");
var num = parseInt(arr[arr.length - 1]);
arr.splice(-1, 1);
var str = arr.join ('-');
for (n = 1; n <= 5; n++) {
num++;
ser = str + '-' + num;
$('#result').html($('#result').html() + '<br>' + ser);
}
});
div{width:80%;margin-top:30px;background:wheat;}
<input id="in" type="text" value="ABC123-DE45-1" />
<button>Go</button>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I figured it out, and am posting the question for future seekers.
JS Fiddle demo
HTML:
<input id="in" type="text" value="A48-DBD7-395" />
<button>Go</button>
<div id="result"></div>
js/jQ:
$('button').click(function(){
var ser = $('#in').val();
var num = parseInt(ser.match(/\d+$/));
var pos = ser.indexOf(num);
var str = ser.slice(0,pos);
for (n=1;n<=5;n++){
num++;
ser = str + num;
$('#result').html( $('#result').html() +'<br>'+ser);
}
});
const s = "A48-DBD7-398";
s.split('-').reduce((a,b)=>{
if(Number(b)){b = Number(b) + 1}
return a +'-'+ b;
})
> "A48-DBD7-399"

Remove/ truncate leading zeros by javascript/jquery

Suggest solution for removing or truncating leading zeros from number(any string) by javascript,jquery.
You can use a regular expression that matches zeroes at the beginning of the string:
s = s.replace(/^0+/, '');
I would use the Number() function:
var str = "00001";
str = Number(str).toString();
>> "1"
Or I would multiply my string by 1
var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"
Maybe a little late, but I want to add my 2 cents.
if your string ALWAYS represents a number, with possible leading zeros, you can simply cast the string to a number by using the '+' operator.
e.g.
x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"
x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)
if your string doesn't represent a number and you only need to remove the 0's use the other solutions, but if you only need them as number, this is the shortest way.
and FYI you can do the opposite, force numbers to act as strings if you concatenate an empty string to them, like:
x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string
hope it helps somebody
Since you said "any string", I'm assuming this is a string you want to handle, too.
"00012 34 0000432 0035"
So, regex is the way to go:
var trimmed = s.replace(/\b0+/g, "");
And this will prevent loss of a "000000" value.
var trimmed = s.replace(/\b(0(?!\b))+/g, "")
You can see a working example here
parseInt(value) or parseFloat(value)
This will work nicely.
I got this solution for truncating leading zeros(number or any string) in javascript:
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
Simply try to multiply by one as following:
"00123" * 1; // Get as number
"00123" * 1 + ""; // Get as string
1. The most explicit is to use parseInt():
parseInt(number, 10)
2. Another way is to use the + unary operator:
+number
3. You can also go the regular expression route, like this:
number.replace(/^0+/, '')
Try this,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
More here
You should use the "radix" parameter of the "parseInt" function :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt
parseInt('015', 10) => 15
if you don't use it, some javascript engine might use it as an octal
parseInt('015') => 0
If number is int use
"" + parseInt(str)
If the number is float use
"" + parseFloat(str)
const number = '0000007457841';
console.log(+number) //7457841;
OR number.replace(/^0+/, '')
Regex solution from Guffa, but leaving at least one character
"123".replace(/^0*(.+)/, '$1'); // 123
"012".replace(/^0*(.+)/, '$1'); // 12
"000".replace(/^0*(.+)/, '$1'); // 0
I wanted to remove all leading zeros for every sequence of digits in a string and to return 0 if the digit value equals to zero.
And I ended up doing so:
str = str.replace(/(0{1,}\d+)/, "removeLeadingZeros('$1')")
function removeLeadingZeros(string) {
if (string.length == 1) return string
if (string == 0) return 0
string = string.replace(/^0{1,}/, '');
return string
}
One another way without regex:
function trimLeadingZerosSubstr(str) {
var xLastChr = str.length - 1, xChrIdx = 0;
while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
xChrIdx++;
}
return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}
With short string it will be more faster than regex (jsperf)
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
Use "Math.abs"
eg: Math.abs(003) = 3;
console.log(Math.abs(003))

how to parse string to int in javascript

i want int from string in javascript how i can get them from
test1 , stsfdf233, fdfk323,
are anyone show me the method to get the integer from this string.
it is a rule that int is always in the back of the string.
how i can get the int who was at last in my string
var s = 'abc123';
var number = s.match(/\d+$/);
number = parseInt(number, 10);
The first step is a simple regular expression - \d+$ will match the digits near the end.
On the next step, we use parseInt on the string we've matched before, to get a proper number.
You can use a regex to extract the numbers in the string via String#match, and convert each of them to a number via parseInt:
var str, matches, index, num;
str = "test123and456";
matches = str.match(/\d+/g);
for (index = 0; index < matches.length; ++index) {
num = parseInt(matches[index], 10);
display("Digit series #" + index + " converts to " + num);
}
Live Example
If the numbers really occur only at the ends of the strings or you just want to convert the first set of digits you find, you can simplify a bit:
var str, matches, num;
str = "test123";
matches = str.match(/\d+/);
if (matches) {
num = parseInt(matches[0], 10);
display("Found match, converts to: " + num);
}
else {
display("No digits found");
}
Live example
If you want to ignore digits that aren't at the end, add $ to the end of the regex:
matches = str.match(/\d+$/);
Live example
var str = "stsfdf233";
var num = parseInt(str.replace(/\D/g, ''), 10);
var match = "stsfdf233".match(/\d+$/);
var result = 0; // default value
if(match != null) {
result = parseInt(match[0], 10);
}
Yet another alternative, this time without any replace or Regular Expression, just one simple loop:
function ExtractInteger(sValue)
{
var sDigits = "";
for (var i = sValue.length - 1; i >= 0; i--)
{
var c = sValue.charAt(i);
if (c < "0" || c > "9")
break;
sDigits = c + sDigits;
}
return (sDigits.length > 0) ? parseInt(sDigits, 10) : NaN;
}
Usage example:
var s = "stsfdf233";
var n = ExtractInteger(s);
alert(n);
This might help you
var str = 'abc123';
var number = str.match(/\d/g).join("");
Use my extension to String class :
String.prototype.toInt=function(){
return parseInt(this.replace(/\D/g, ''),10);
}
Then :
"ddfdsf121iu".toInt();
Will return an integer : 121
First positive or negative number:
"foo-22bar11".match(/-?\d+/); // -22
javascript:alert('stsfdf233'.match(/\d+$/)[0])
Global.parseInt with radix is overkill here, regexp extracted decimal digits already and rigth trimmed string

Categories

Resources