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

如何为JavaScript字符串匹配代码添加仅提取名称的条件?

Got it, let's work through this. The core issue here is filtering your matches to only keep proper names (like "Jim") instead of regular words from your array.

First, let's establish a clear way to identify a "name"—since your example uses a person's name, the most common and reliable pattern is that proper names start with an uppercase letter, followed by lowercase letters (you can tweak this rule if you have edge cases like hyphenated names or initials).

Here's how to update your code with this check:

const title = document.getElementById("title").value;
const cat_list = document.getElementById("category-all").textContent
  .replace(/\n\n/g, "\n")
  .replace(/^\s*/g, "")
  .trim()
  .split("\n");

// Helper function to check if a string matches our "name" criteria
function isProperName(str) {
  // Basic regex: starts with uppercase, followed by one or more lowercase letters
  // Adjust this regex if you need to support hyphens, apostrophes, etc.
  const nameRegex = /^[A-Z][a-z]+$/;
  return nameRegex.test(str);
}

// Loop through the category list to find matching names
for (let i = 0; i < cat_list.length; i++) {
  const currentItem = cat_list[i].trim(); // Clean up any accidental whitespace
  // Check two things: does the item exist in the title, AND is it a proper name?
  if (title.includes(currentItem) && isProperName(currentItem)) {
    console.log("Matching name found:", currentItem);
    return currentItem; // Return the first valid name we find
  }
}

// If no valid name is found, return null or handle this case as needed
return null;

Key adjustments explained:

  • Added a isProperName helper function: This uses a regular expression to validate that the string follows the typical proper name format. If you need to support edge cases (like "Mary-Anne" or "O'Conner"), you can update the regex to something like /^[A-Z][a-z]+([-' ][A-Z][a-z]+)*$/.
  • Trimmed currentItem: Ensures we don't accidentally match strings with extra whitespace (common if your category list has line breaks with spaces).
  • Combined conditions: We only return an item if it exists in the title and meets our name criteria—this filters out matches like "free" or "wrestling" that don't qualify as names.

If you need to collect all matching names (instead of just the first one), you can modify the code to push valid matches to an array and return that array at the end:

const matchingNames = [];
for (let i = 0; i < cat_list.length; i++) {
  const currentItem = cat_list[i].trim();
  if (title.includes(currentItem) && isProperName(currentItem)) {
    matchingNames.push(currentItem);
  }
}
return matchingNames; // Returns an array of all valid names found

内容的提问来源于stack exchange,提问作者mohamed amin mansourkhaki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:25:24