Question: If a string is longer than 3 characters, return only the first 3 characters in lower case. If the string is less than 3 characters, then return the string in capital letters.
I know the question may be interpreted in a couple of ways (a) convert the first 3 characters in lower case, but return the whole sentence, (b) identify the first 3 characters initially written in lower case and return those. My solution is based on option (b) but i do have a question that came up when using the "g" modifier in my regular expression. If I were to write /[a-z]/g in regExp variable, then the result changes. In the example below, it would return "iei" instead of "ife." I don't know why. Wondering if someone might know.
function newString(sentence){
let regExp = /[a-z]/;
let newStr = [];
if(sentence.length > 3) {
for(let i = 0; i < sentence.length; i++){
if(regExp.test(sentence[i]) && newStr.length < 3){
newStr.push(sentence[i]);
}
}
return newStr.join("");
} else {
return sentence.toUpperCase();
}
}
console.log(newString("Life is a gift"));