skip to Main Content

I want it to display "Dr. House" instead of Dr. Greg house and I am only allowed to modify "const re = /^(w+.s)(w+sw+)$/;". Can anyone help me?

here is the code

const userName = "Dr. Greg House"; // Code will also be tested with "Mr. Howard Wolowitz"

/* Your solution goes here */
const re = /^(w+.s)(w+sw+)$/;
const result = re.exec(userName);

console.log(result[1] + " " + result[2]);

2

Answers


  1. Use capturing groups only for the words you need to keep:

    const userName = "Dr. Greg House"; // Code will also be tested with "Mr. Howard Wolowitz"
    
    /* Your solution goes here */
    const re = /^(w+.)sw+s(w+)$/;
    const result = re.exec(userName);
    
    console.log(result[1] + " " + result[2]);
    Login or Signup to reply.
  2. A .replace() combined with a .trim() will do the job just as well:

    const names = ["Dr. Greg House", "Mr. Howard Wolowitz", "Dr. Amy Farrah Fowler"];
    const res=names.map(n=>{
      return n.trim().replace(/s+S+/,"")
    });
    
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search