0

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"));
huan feng
  • 7,307
  • 2
  • 32
  • 56
Veronica
  • 45
  • 5

1 Answers1

0

The "g" modifier specifies a global match.

A global match finds all matches (compared to only the first).

https://www.w3schools.com/jsref/jsref_regexp_g.asp

But for this example, both cases should have been working.

  • 1
    Both cases (with `g` and without `g`) work differently, you can modify the snippet in the question to use `/g` to see for yourself. The reason why they're different is explained here if you'd like to know why: [Why does a RegExp with global flag give wrong results?](https://stackoverflow.com/q/1520800) – Nick Parsons Feb 21 '23 at 02:36
  • @NickParsons the thread you posted well explained the reason – huan feng Feb 21 '23 at 03:04