Skip to content

Instantly share code, notes, and snippets.

@LearningNerd
Created June 9, 2018 05:21
Show Gist options
  • Save LearningNerd/100185e3156c868d8139d06d409bc384 to your computer and use it in GitHub Desktop.
Save LearningNerd/100185e3156c868d8139d06d409bc384 to your computer and use it in GitHub Desktop.
This code snippet finds 1 to 2 digit numbers in a string matching a pattern (hard-coded for now), and replaces each number with itself + 1
/////////////////////////////////////////////////////////////////////////
// Replacing parts of a string with incremental numbers
////////////////////////////////////////////////////////////////////////
// This code snippet finds 1 to 2 digit numbers in a string matching a pattern
// (hard-coded for now), and replaces each number with itself + 1
// **** For a very specific use case, but easy enough to repurpose as needed :)
// Regex matches 1 to 2 digits preceded by the string ":
function replaceNumbersWithIncrement(givenString) {
let re = /": \d{1,2}/gi;
objString.replace(re, replacer);
// For each match, get the number itself, increment it, and replace!
function replacer(match) {
let incrementedMatch = parseInt(match.substring(2), 10) + 1;
console.log( incrementedMatch );
return '": ' + incrementedMatch;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment