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

如何使用JavaScript提取关键字后5位字符串并返回为数组(含重复场景)

JavaScript: Extract 5 Characters After a Keyword (Single & Multiple Occurrences)

Let's break down how to solve both of your requirements using regular expressions—they're flexible enough to handle edge cases like special characters in the keyword or variable whitespace after it.

Scenario 1: Extract the 5 characters after the first occurrence of the keyword

If you only need the first match, we'll use a non-global regex to find it and wrap the result in an array (as requested).

Solution Code

function escapeRegExp(string) {
  // Escape regex special characters to avoid issues with keywords containing ., *, etc.
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function extractFirstAfterKeyword(str, keyword, length = 5) {
  const escapedKeyword = escapeRegExp(keyword);
  // Regex matches the keyword, followed by any whitespace, then captures the next `length` characters
  const regex = new RegExp(`${escapedKeyword}\\s*(.{${length}})`);
  const match = str.match(regex);
  
  // Return array with the captured value, or empty array if no match found
  return match ? [match[1]] : [];
}

// Test with your example
const exampleStr = "My secret code is 12345 and his secret code is 67890";
const keyword = "secret code is";
console.log(extractFirstAfterKeyword(exampleStr, keyword)); // Output: ["12345"]

Explanation

  • escapeRegExp ensures keywords with special characters (like . or *) don't break the regex.
  • \\s* handles any number of whitespace characters (spaces, tabs) after the keyword, making the solution more flexible.
  • We wrap the result in an array even for single matches to align with your requirement.

Scenario 2: Extract the 5 characters after every occurrence of the keyword

For multiple matches, we'll use a global regex (g flag) to iterate through all occurrences and collect all captured values.

Solution Code

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function extractAllAfterKeyword(str, keyword, length = 5) {
  const escapedKeyword = escapeRegExp(keyword);
  const regex = new RegExp(`${escapedKeyword}\\s*(.{${length}})`, 'g');
  const matches = [];
  let match;
  
  // Loop through all matches and collect each captured group
  while ((match = regex.exec(str)) !== null) {
    matches.push(match[1]);
  }
  
  return matches;
}

// Test with your example
console.log(extractAllAfterKeyword(exampleStr, keyword)); // Output: ["12345", "67890"]

Explanation

  • The g flag tells the regex to find all matches in the string instead of stopping at the first one.
  • We use regex.exec() in a loop to grab each match, pushing the 5-character result into our array every time.
  • This works reliably even if the keyword appears multiple times in the string.

Quick Customization Tips

  • To match only alphanumeric characters: Replace .{${length}} with \\w{${length}}
  • To match only digits: Replace .{${length}} with \\d{${length}}

内容的提问来源于stack exchange,提问作者suresh mg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 20:28:09