regex 使用正则表达式删除名字

ijnw1ujt  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(151)

我希望它显示“博士。“房子”而不是医生。Greg House和我只允许修改“const re = /^(\w+.\s)(\w+\s\w+)$/;“谁能帮帮我?
这里是代码

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

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

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

cs7cruho1#

仅对需要保留的单词使用捕获组:

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

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

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

xfb7svmp2#

.replace().trim()结合使用也可以完成这项工作:

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);

相关问题