Increment numbers at end of alphanumeric string in JavaScript - 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"

Related

From Decimal to Binary system

I want to make an easy website because I want to learn javascript. The website will have just one (number) input named "number". After clicking on submit button the website will convert the number from decimal to binary system and show the answer.
This is the javascript part that should convert the number and show the answer in a div with ID = result:
var selectedNumber = document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k.append(a);
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k.append(b);
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k.append(b);
for i in reversed(k){
document.getElementById("result").innerHETML = i;
}
Unfortunately, I don't have much experience using javascript and this code doesn't work. I've made a similar program in python and based this code on that in python.
Here's the corrected code:
Tip - Whenever you have to glue two numbers to form a string make sure to do 1 + "" +2
var selectedNumber = 105;//document.getElementByName("number").value;
var k = [];
var a = 0;
var b = 1;
var output = '';
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k=k+""+a;
selectedNumber = Math.floor(selectedNumber/2);
}
else{
k=k+""+b;
selectedNumber = Math.floor(selectedNumber/2);
}
}
k=k+""+b;
console.log(k);
//document.getElementByName("number").value = k;
Simplest way is to use toString(2) method.
let a =7
console.log(a.toString(2))
I have made some minor changes to your code. removed redundant lines. i am appending values to a front of string instead of an array ( which you later reverse and join).
function handle(){
let selectedNumber = document.getElementById("number").value;
let k = '',a = 0, b = 1;
while (selectedNumber > 1){
if(selectedNumber%2 < 1){
k= a+k
}
else{
k=b+k
}
selectedNumber = Math.floor(selectedNumber/2);
}
k=b+k;
document.getElementById("result").innerHTML = k;
}
#result{
color: green;
font-size:25px;
}
<input id='number' placeholder='enter value'></input>
<button onClick=handle()>Convert to binary</button>
<div id='result'></div>
It's a whole lot simpler than that. The .toString() method takes an optional argument that can be used to convert a number to a different numerical base system, like its binary, octal or hex values.
Prepending the input's value with +, forces the input's value to become a number.
document.querySelector("button").addEventListener("click", function(){
let number = +document.querySelector("input").value; // Convert input into a string
console.clear();
console.log("The decimal: " + number + " converted to a binary is: " + number.toString(2));
console.log("The decimal: " + number + " converted to an octal is: " + number.toString(8));
console.log("The decimal: " + number + " converted to a hex is: " + number.toString(16));
});
<input><button>Convert!</button>
For this goal, actually you can forget all your code and simple use Number.prototype.toString(). It takes an optional argument of the base you want to use for convert the number to string.
Example:
const convert = () =>
{
let number = document.getElementById("iNumber").value;
binNumber = Number.parseInt(number, 10).toString(2);
document.getElementById("dRes").innerHTML = binNumber;
};
<input id="iNumber" type="number">
<button id="btnToBinary" onclick="convert()">
Convert To Binary
</button>
<div id="dRes"></div>

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));

Wrap each digitand prepend zeros up to X digits

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>");
}

Javascript multiple digit index

I have searched around the net and the solution must be so simple no one has asked?
I just wanted to use an index like + i + to return 001, 002, 003, etc
How about
('000' + i).substr(-3);
So something like this?
function number_pad(num,len) {
num = ""+num;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: number_pad(i,3);
Alternatively, extend the native object:
Number.prototype.pad(len) {
var num = ""+this;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: i.pad(3);
For future reference, this is called zerofill or zero-padding.
function paddedNumber(n) {
// A string containing the fully padded zero value.
var zeroes = "000";
// The number as a string.
var numstr = "" + n;
var nDigits = numstr.length;
// Keep any sign at the front.
var sign = "";
if (/^[\+\-]/.test(numstr)) {
sign = numstr.charAt(0);
numstr = numstr.substring(1);
}
// Concatenates the number with just enough zeroes.
// No padding if itoa is already longer than the pad.
return sign + zeroes.substring(nDigits) + numstr;
}

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