How to increment a string in Javascript - javascript

Let's say I have the following string:
aRandomString
I'm then checking my database to see if that string has been used before (or if there's any string that starts with the given one). If it has, I'd like to increment it. The result would be the following:
aRandomString1
If that string exists, it would become aRandomString2, and so on. I'm assuming I need to complete the following steps: 1. Check for trailing numbers or set to 0, 2. Increment those trailing numbers by 1, append that number to the original string. Just trying to figure out a solid way to accomplish this!
Update
This is what I have so far:
var incrementString = function( str ){
var regexp = /\d+$/g;
if( str.match(regexp) )
{
var trailingNumbers = str.match( regexp )[0];
var number = parseInt(trailingNumbers);
number += 1;
// Replace the trailing numbers and put back incremented
str = str.replace(/\d+$/g , '');
str += number;
}else{
str += "1";
}
return str;
}
I feel like this should be easier though.

function incrementString(str) {
// Find the trailing number or it will match the empty string
var count = str.match(/\d*$/);
// Take the substring up until where the integer was matched
// Concatenate it to the matched count incremented by 1
return str.substr(0, count.index) + (++count[0]);
};
If the match is the empty string, incrementing it will first cast the empty string to an integer, resulting the value of 0. Next it preforms the increment, resulting the value of 1.

I had to keep the leading zeros in the number, this is how I did it:
function incrementString (string) {
// Extract string's number
var number = string.match(/\d+/) === null ? 0 : string.match(/\d+/)[0];
// Store number's length
var numberLength = number.length
// Increment number by 1
number = (parseInt(number) + 1).toString();
// If there were leading 0s, add them again
while (number.length < numberLength) {
number = "0" + number;
}
return string.replace(/[0-9]/g, '').concat(number);
}

Related

issue with substring indexing

Instructions for this kata:
In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each letter occurs only once.
It seems that my code is indexing the strings differently per function call on this one. for example, on the first test "abcd", the starting index is shown as 0, which is correct, and on the second example, "himjlk", the
var subString = alphabet.substring(startIndex, length);
returns "g", instead of "h"
troubleshooting this section
var length = orderedString.length;
//startChar for string comparison
var startChar = orderedString.charAt(0);
//find index in aphabet of first character in orderedString.
var startIndex = alphabet.indexOf(startChar);
//create substring of alphabet with start index of orderedString and //orderedString.length
var subString = alphabet.substring(startIndex, length);
function solve(s) {
//alphabet string to check against
const alphabet = `abcdefghijklmnopqrstuvwxyz`;
//check s against alphabet
//empty array to order input string
var ordered = [];
//iterate through alphabet, checking against s
//and reorder input string to be alphabetized
for (var z in alphabet) {
var charToCheck = alphabet[z];
for (var i in s) {
if (charToCheck === s[i]) {
ordered.push(s[i]);
}
//break out of loop if lengths are the same
if (ordered.length === s.length) {
break;
}
}
if (ordered.length === s.length) {
break;
}
}
//join array back into string
var orderedString = ordered.join(``);
//length for future alphabet substring for comparison
var length = orderedString.length;
//startChar for string comparison
var startChar = orderedString.charAt(0);
//find index in aphabet of first character in orderedString.
var startIndex = alphabet.indexOf(startChar);
//create substring of alphabet with start index of orderedString and orderedString.length
var subString = alphabet.substring(startIndex, length);
//return if the two are a match
return subString == orderedString ? true : false;
}
console.log(solve("abdc")); //expected `true`
console.log(solve("himjlk")); // expected `true`
console.log(solve("abdc")); should provide the substring "abcd" and return true, which it does.
console.log(solve("himjlk")); should put together "hijklm" and return true, but instead gives me g based on index 6 of alphabet, not sure why it's doing this, should be index 7 "h" returns false based upon this error.
The problem is that you're using substring() instead of substr(). Though that might sound similar there's a difference.
With substring the second parameter doesn't determine the length as you might have expected. It's actually the index to stop.
That your function works as expected with the string abcd is pure coincidence since in this case the length from index 0 and the end index are the same.
function solve(s){
const alphabet = `abcdefghijklmnopqrstuvwxyz`;
var ordered = [];
for(var z in alphabet){
var charToCheck = alphabet[z];
for(var i in s){
if(charToCheck === s[i]){
ordered.push(s[i]);
}
if(ordered.length === s.length){ break; }
}
if(ordered.length === s.length){ break; }
}
var orderedString = ordered.join(``);
var length = orderedString.length;
var startChar = orderedString.charAt(0);
var startIndex = alphabet.indexOf(startChar);
var subString = alphabet.substr(startIndex, length);
return subString == orderedString ? true: false;
}
console.log(solve("himjlk"));
You approach is also correct. I am giving another solution using sort() and charCodeAt. Instead of getting the index and then breaking string into parts to compare just use includes()
function check(str){
let org = [...Array(26)].map((x,i) => String.fromCharCode(i + 97)).join('');
str = str.split('').sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0)).join('');
return org.includes(str);
}
console.log(check("abdc"))//true
console.log(check("himjlk"));//true
console.log(check("himjlkp"));//false
Explanation:
Frist Line:
let org = [...Array(26)].map((x,i) => String.fromCharCode(i + 97)).join('');
is use to create string "abcd....xyz".
[...Array(26)] will create an array of 26(no of alphabets) undefined values.
map() is a function which takes a callback and the create an array based the values of previous. The first parameter of map() callback x is the value itself which will be undefined(because all the values in array are undefined).
i the second parameter will be the index of the element. Which will start from 0 upto 25.
String.fromCharCode is function which takes a character code(integer) and then convert it to string. For example character code for a is 97 so String.fromCharCode(97) will return "a". 98 for "b", 99 for "c" etc.
So after map() an array like ["a","b"....,"z"] will be generated.
-join() will convert that to string
Second Line:
str is given string. str.split('') will convert string to array. For example
if str is "abdc" it will return ["a","b","d","c"]
sort() is the array method which takes the callback. The two parameters are two values to be compared during sort(). a and b are two values.
charCodeAt acts in reverse as String.fromCharCode. For example "a".charCodeAt(0) will be return 97 for "b" it will 98 and so on.
a.charCodeAt(0) - b.charCodeAt(0) which is returned from sort() will sort array is ascending order. And join() will convert array to string.
So string "abdc" will become "abcd"
Third Line:
The third line is the main one. org is string "abcdefghijklmnopqrstuvwxyz". Now if any string is a substring of this string then it means its in alphabetical order. So we check the sorted str is includes in the string or not.
You can clean up the second line by
str = str.split('').sort().join('');
Because if no callback is passed to sort() it will sort in default order. Mean alphabetical order.

I need to take an inputted string, take the non-numeric characters out, and then if the string begins with a 1, remove the 1

function changeNumber(e) {
var phoneNumber = e.replace(/\D/g, '');
if (phoneNumber.startsWith("1")) {
var finalNumber = phoneNumber.slice(0);
return finalNumber;
} else {
return phoneNumber;
};
};
console.log(changeNumber("+1 (234)-567.8995"));
Desired result should be: 2345678995 but I am getting 12345678995. It's like it's not running through the if statement.
You need to use String#slice starting from index 1, because you want to omit the first character at index 0.
phoneNumber.slice(0)
returns a copy of the string, as an assignment of the variable, but
phoneNumber.slice(1)
returns the string from index 1 and all following characters.
function changeNumber(e) {
var phoneNumber = e.replace(/\D/g, '');
return phoneNumber.startsWith("1")
? phoneNumber.slice(1)
: phoneNumber;
}
console.log(changeNumber("+1 (234)-567.8995"));
Made a more concise function without conditionals
\D matches all non-digit characters.
^1 matches 1 if it is the first character in the string.
function changeNumber(e) {
return e.replace(/\D/g, '').replace(/^1/g, '');
};
console.log(changeNumber("+1 (234)-567.8995"));

Regex Constructor doesn't work for matching a variable in a string word

I am trying to find number of occurrences of a string letter(variable) in a string word, using a regex constructor but it doesn't work.
function getNumberOfOccurrences()
{
//get input from user:
var inputWord = document.getElementById("wordInputField").value;
inputWord = inputWord+""; // turn it into a string
var inputLetter = document.getElementById("letterInputField").value;
inputLetter = inputLetter+""; // turn it into a string
if(checkInput(inputWord , inputLetter)) // other function that checks the input
{
var rgxInputLetter = new RegExp(inputLetter, "g"); //use regex constructor for the match function:
var resultArray = inputWord.match(rgxInputLetter); // use match to find occurrences. match returns an array
var occurences = resultArray.length; // length of array should be the occurrences
if(isNaN(occurences) && occurences >= 0) // check that match function worked and an array was returned
{
document.getElementById("resultField").innerHTML = "There are "+occurences + " occurrences of: \""+inputLetter+"\" in the word: \""+inputWord+"\"";
}
else
{
document.getElementById("resultField").innerHTML = "There are no occurrences of: \""+inputLetter+"\" in the word: \""+inputWord+"\"";
}
}
}
It always gives me an error that the resultArray is null.
even if I write inputLetter = "a" or inputWord = "something" just before the match function.
Why it doesn't work?
Found that it actually works , and the problem was the last if condition isNaN(occurences).
The condition as it is checks that occurences is not a number.
Should have added a ! sign. -_-
so this fixed it:
if( ! isNaN(occurences) && occurences >= 0)

How to extract last characters of type number javascript/jquery

I have some strings like:
row_row1_1,
row_row1_2,
row_row1_13,
row_row1_287,
...
and I want to take the last numbers of that strings, ut can be 1, 2, 13 or 287. That strings are generated automatically and I can't control if there is going to be 1 number, 2 numbers, 3 numbers...
I would like to make a function that takes the last number character, or the numbers after the second '_' character. is there any idea?
Thank you very much!
If your strings always follow this pattern str_str_str then you can use the split method and get the 2ยบ index of the array, like this:
var number = str.split('_')[2];
As #PaulS said, you can always use regex for that purpose:
var getLastNumbers = function(str)
{
return str.replace(/.+(_)/, '');
};
getLastNumbers("row_row1_287"); // Will result -> 287
Fiddle
Taking the last numeric characters
function getNumericSuffix(myString) {
var reversedString = myString.split('').reverse().join('');
var i, result="";
for(i = 0; i < reversedString.length; i++) {
if(!isNaN(reversedString[i])) {
result = reversedString[i] + result;
} else break;
}
return parseInt(result); // assuming all number are integers
}

Replace any number with a specific number from variable

I have link like this foo.net/index.php?page=15
And I need to replace any number after page=xxx and get the new number from variable
This my current code just replace 15 to 16
var num = 16,
// What if the str = foo.net/index.php?page=10
str = 'foo.net/index.php?page=15',
n = str.replace('15',num);
$('span').html(n);
You can check the code in http://jsfiddle.net/KMsv7/
If you want to select and replace numbers in a string you can use regular expression:
// Replacing macting number with the specified value
var n = str.replace(/\d+/, num);
In case that you want to add/subtract/divide/multiply the matching value, you can also use the callback function of the .replace() method:
var n = str.replace(/\d+/, function(number) {
return number + 1;
});
Reference.

Categories

Resources