I’m working with strings that look like this:
JavaScript
x
2
1
"do3mi3so3 la3 ti4 do5 re5 mi5 /2 x2 fa4"
2
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:
JavaScript
1
2
1
"do3mi3so3 la4 ti5 do6 re6 mi6 /2 x2 fa5"
2
Here is my code:
JavaScript
1
19
19
1
function is_numeric(str){
2
return /^d+$/.test(str);
3
}
4
5
6
function change_octave(notes,split_point){
7
for(var i=(split_point-1);i<notes.length;i++){
8
if(is_numeric(notes[i])==true){
9
notes[i]='' + parseInt(notes[i])+1;
10
//console.log(parseInt(notes[i])+1) //these numbers are incrementing
11
}
12
if(notes[i]=='/'||notes[i]=='x'){
13
i = i+3;
14
}
15
}
16
return notes;
17
}
18
var notes = "do3mi3so3 la3 ti4 do5 re5 mi5 /2 x2 fa4";
19
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.
JavaScript
1
19
19
1
function is_numeric(str){
2
return /^d+$/.test(str);
3
}
4
5
function change_octave(notesStr,split_point){
6
const notes = notesStr.split('');
7
for(var i=(split_point-1);i<notes.length;i++){
8
if(is_numeric(notes[i])==true){
9
const newValue = parseInt(notes[i]) + 1;
10
notes[i] = '' + newValue;
11
}
12
if(notes[i]=='/'||notes[i]=='x'){
13
i = i+3;
14
}
15
}
16
return notes.join('');
17
}
18
var notes = "do3mi3so3 la3 ti4 do5 re5 mi5 /2 x2 fa4";
19
console.log(change_octave(notes,4));