You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求JS正则表达式:移除姓名头衔并按规则清理姓名内容

Clean Names by Removing Titles in JavaScript

Got it, let's solve this name cleaning problem with regex step by step. You need to handle two key rules: removing everything after the last comma, and stripping titles before the first word without a period. Here's how to do it properly:

Step 1: Remove Content After the Last Comma

Your initial regex was close, but to include the comma itself, use this pattern to match the comma and all content after it, then replace with an empty string:

// Remove comma and everything after it
name = name.replace(/(,.*)$/, '').trim();

This turns Ian Smith, Phd into Ian Smith perfectly.

Step 2: Strip Prefix Titles

To remove all titles before the first word without a period (like Dr., Prof. Dr.), we can target the prefixes that follow the "word + period + optional space" pattern. Use this regex to match and remove those prefixes:

// Remove all leading titles (e.g., Dr., Prof. Dr.)
name = name.replace(/^(?:\w+\.\s*)+/, '').trim();

Let's break down this regex:

  • ^ anchors to the start of the string
  • (?:\w+\.\s*)+ is a non-capturing group that matches one or more instances of:
    • \w+: One or more word characters (the title text)
    • \.: A literal period
    • \s*: Optional whitespace after the period

Full Function with Test Cases

Combine both steps into a reusable function:

function cleanPersonName(name) {
  // Handle comma suffix first
  let cleanedName = name.replace(/(,.*)$/, '').trim();
  // Strip leading titles
  cleanedName = cleanedName.replace(/^(?:\w+\.\s*)+/, '').trim();
  return cleanedName;
}

// Test all your examples
console.log(cleanPersonName("Dr. Ian Smith")); // "Ian Smith"
console.log(cleanPersonName("Prof. Dr. Ian Smith")); // "Ian Smith"
console.log(cleanPersonName("Ian Smith, Phd")); // "Ian Smith"
console.log(cleanPersonName("Dr. Ian S.")); // "Ian S."

This works for all your test cases because:

  • It first eliminates any trailing comma and credentials (like Phd after the comma)
  • Then it strips all leading titles that end with a period, leaving the core name intact—even if the name has an initial with a period (like Ian S.).

内容的提问来源于stack exchange,提问作者Shezan Kazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:36:36