You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

正则需求:提取赋值给属性的JavaScript函数内容

Extract Function Content from the Given Code Snippet

Got it, let's tackle this problem. You want to pull out the content inside the foobar function's curly braces from that code string, and your existing regexes aren't cutting it because they can't properly exclude everything before the function's opening brace (and might fail if there are nested braces later). Here are two reliable solutions depending on your use case:

Case 1: No Nested Curly Braces in the Function Body

If your function content doesn't have nested {} (like the example you gave with just a comment), a targeted regex will work perfectly. This regex specifically targets the lib.foobar function definition and captures the content inside its braces:

const code = '(lib.foobar = function(mode, startPosition, loop) { // 待提取内容 }).prototype = getMCSymbolPrototype(lib.foobar, new cjs.Rectangle(0, 0, 59.7, 59.4), null);';
const regex = /lib\.foobar\s*=\s*function\([^)]*\)\s*({([\s\S]+?)})/;
const matchResult = code.match(regex);

if (matchResult) {
  // matchResult[2] holds the content inside the function's braces
  const functionContentStr = matchResult[2];
  console.log(functionContentStr); // Output: " // 待提取内容 "
}

Regex Breakdown:

  • lib\.foobar: Matches the exact function name (escaping the dot since regex treats it as a wildcard)
  • \s*=\s*: Accounts for any whitespace around the equals sign
  • function\([^)]*\): Matches the function declaration and its parameters (captures everything inside the parentheses)
  • \s*: Ignores any whitespace before the opening brace
  • ({([\s\S]+?)}): Captures the opening brace, then all content (including newlines) until the first closing brace (non-greedy match to stop at the correct brace)

Case 2: Nested Curly Braces in the Function Body

If your function might have nested braces (like { let obj = { key: val }; }), regex alone can't handle balanced braces reliably. Instead, use a simple stack-based approach to count braces and find the correct closing one:

const code = '(lib.foobar = function(mode, startPosition, loop) { let nestedObj = { x: 1, y: 2 }; // 带嵌套的待提取内容 }).prototype = getMCSymbolPrototype(lib.foobar, new cjs.Rectangle(0, 0, 59.7, 59.4), null);';

// Locate the start of the foobar function definition
const functionStartMarker = 'lib.foobar = function';
const startIndex = code.indexOf(functionStartMarker);

if (startIndex !== -1) {
  // Find the first opening brace after the function declaration
  const openingBraceIndex = code.indexOf('{', startIndex);
  
  if (openingBraceIndex !== -1) {
    let braceCount = 1;
    let currentPos = openingBraceIndex + 1;
    
    // Traverse the code to count braces until we find the matching closing one
    while (currentPos < code.length && braceCount > 0) {
      if (code[currentPos] === '{') braceCount++;
      else if (code[currentPos] === '}') braceCount--;
      currentPos++;
    }
    
    // Extract the content between the opening and matching closing brace
    const functionContentStr = code.slice(openingBraceIndex + 1, currentPos - 1);
    console.log(functionContentStr); // Output: " let nestedObj = { x: 1, y: 2 }; // 带嵌套的待提取内容 "
  }
}

This method is far more robust for real-world code where function bodies often have nested structures.

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

火山引擎 最新活动