There are many ways to accomplish this, you could for example have a series of if-else statements or a switch statement, I would suggest a different option though:
var str = 'hello',
actions = { // Define actions (function to call) you want for specific characters
h: function () {
// Do something if character was 'h'
console.log('h');
},
l: function () {
// Do something if character was 'l'
console.log('l');
},
o: function () {
// Do something if character was 'o'
console.log('o');
}
};
for (var i = 0; i < str.length; i++) {
if (actions[str[i]]) { // If there is an action/function defined for the current character then call the function
actions[str[i]]();
}
}
This you you don't have to "know" what character you are currently on in the loop, only if something should happen for it.
And for reference, achieving the same thing with if-else statements:
var str = 'hello';
for (var i = 0; i < str.length; i++) {
if (str[i] === 'h') {
// Do something if character was 'h'
console.log('h');
}
else if (str[i] === 'l') {
// Do something if character was 'l'
console.log('l');
}
else if (str[i] === 'o') {
// Do something if character was 'o'
console.log('o');
}
}
And with switch statement:
var str = 'hello';
for (var i = 0; i < str.length; i++) {
switch (str[i]) {
case 'h':
// Do something if character was 'h'
console.log('h');
break;
case 'l':
// Do something if character was 'l'
console.log('l');
break;
case 'o':
// Do something if character was 'o'
console.log('o');
break;
}
}