Skip to content
Advertisement

Incrementing specific numbers contained within a string

I’m working with strings that look like this:

"do3mi3so3 la3 ti4 do5 re5 mi5 /2 x2 fa4"

I’d like to increment each number in the string past a specific point exempting numbers next to ‘/’ or ‘x’. For example, if I want to increment all the numbers of the aforementioned string past the point do3mi3so3, I’d expect to get this:

"do3mi3so3 la4 ti5 do6 re6 mi6 /2 x2 fa5"

Here is my code:

function is_numeric(str){
    return /^d+$/.test(str);
}


function change_octave(notes,split_point){
  for(var i=(split_point-1);i<notes.length;i++){
    if(is_numeric(notes[i])==true){
      notes[i]='' + parseInt(notes[i])+1;
      //console.log(parseInt(notes[i])+1) //these numbers are incrementing
    }
    if(notes[i]=='/'||notes[i]=='x'){
      i = i+3;
    }
  }
  return notes;
}
var notes = "do3mi3so3 la3 ti4 do5 re5 mi5 /2 x2 fa4";
console.log(change_octave(notes,4));

Despite the numbers successfully incrementing, the value of the string does not change.

Thanks.

Advertisement

Answer

You can’t actually set the character of a string at a specific index using something like notes[i] = "a". What you can do is split the string into an array, change the values in that array, and then join it back together into a string when you’re done.

function is_numeric(str){
    return /^d+$/.test(str);
}

function change_octave(notesStr,split_point){
  const notes = notesStr.split('');
  for(var i=(split_point-1);i<notes.length;i++){
    if(is_numeric(notes[i])==true){
      const newValue = parseInt(notes[i]) + 1;
      notes[i] = '' + newValue;
    }
    if(notes[i]=='/'||notes[i]=='x'){
      i = i+3;
    }
  }
  return notes.join('');
}
var notes = "do3mi3so3 la3 ti4 do5 re5 mi5 /2 x2 fa4";
console.log(change_octave(notes,4));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement