How to increment the end of string using Javascript [duplicate] - javascript

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

Related

Is there a more efficient algorithm to find this kind of substrings? [duplicate]

This question already has answers here:
How to determine if one string starts with what another ends with
(3 answers)
Closed 3 years ago.
I am writing a function that takes two strings as input parameters: text and pattern.
If text ends with a substring starting at index index and this substring is a start of pattern, then return index.
If there is no such substring, return -1.
I've come up with the following function, but I wonder if there is more efficient solution.
So the question is: is there more efficient algorithm to find such substrings?
function findSubstring(text, pattern) {
let index = -1;
for (let i = 1; i <= text.length; i++) {
const tail = text.substr(-i);
if (pattern.indexOf(tail) === 0) {
index = text.length - i;
}
}
return index;
}
const exampleText = 'const result = items.m';
const examplePattern = '.map((item) => {})';
console.log(findSubstring(exampleText, examplePattern)); // -> 20
I'd check either for a partial match at the end or a full match before that:
const last = text.lastIndexOf(pattern[0]);
if(text.substr(last, last + pattern.length) === pattern.substr(0, text.length - last))
return last;
return text.lastIndexOf(pattern, last);
Although the underlying algorithm is probably less eficcient, this may still run faster due to engine optimizations, wether it is faster in your case needs to be tested.

How can you keep the leading zeros in a new Number() in JavaScript [duplicate]

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

Match function is giving wrong results [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
I'm trying to do match a phone number with a regular expression:
this.Formareamedia.get('ladacontacto').valueChanges.subscribe((lada) => {
let p;
if (lada.length == 5) {
p = '\\d{3}.\\d{4}';
} else {
p = '\\d{4}.\\d{4}';
}
this.Formareamedia.get("telefonocontacto").setValidators(Validators.pattern(new RegExp(p)));
this.Formareamedia.get("telefonocontacto").updateValueAndValidity();
this.ladacontacto = lada;
let telefono = this.Formareamedia.get('telefonocontacto').value;
console.log(new RegExp(p).lastIndex);
if (telefono && telefono.match(new RegExp(p))) {
return null;
} else {
return {
telefono: false
}
}
});
If I put in the lada input (XX) and in the telefono input XXXX-XXXX the function is returning true (a correct result), but if I put in the lada input (XXX) and in the telefono input XXXX-XXXX is returning true a wrong result it is supposed to return false. What's wrong with my function?
You need to anchor your regex to the end of the string, like this:
if (lada.length == 5) {
p = '^\\d{3}.\\d{4}$';
} else {
p = '^\\d{4}.\\d{4}$';
}
Otherwise it will match at least the number you specify (ignoring extra digits).
The same applies to the beginning of string: Specify '^'.
With '$' at the end it will ensure that the string ends with your digits.

positive integer value using jquery/javascript [duplicate]

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

single digit counting using numbers and letters in javascript [duplicate]

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

Categories