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

如何在JavaScript中编写通用代码提取字符串中slot部分及之前的内容?

Universal Solution to Extract Path Up to the Slot Segment

The problem with using indexOf and substr is that they rely on fixed string positions, which break when your input paths have varying structures (like missing a rack segment or including extra subslot details). Regular expressions are the ideal fix here—they dynamically locate the slot segment no matter where it appears in the path.

How It Works

We’ll use a regex pattern that captures everything from the start of the string up to and including the full /slot=X segment (where X is any number of digits). The pattern is:

^.*\/slot=\d+

Breakdown of the pattern:

  • ^ : Anchors the match to the very start of the string.
  • .* : Greedily matches any characters (except newlines) leading up to the slot segment.
  • \/slot=\d+ : Matches the literal /slot= followed by one or more digits (the slot number itself).

JavaScript Implementation

Here’s a reusable function that replaces your static indexOf/substr approach:

function extractUpToSlot(path) {
  const match = path.match(/^.*\/slot=\d+/);
  return match ? match[0] : path; // Fallback to original path if no slot is found
}

// Test with your examples
console.log(extractUpToSlot("/rack=1/shelf=1/slot=12/port=200")); // Output: "/rack=1/shelf=1/slot=12"
console.log(extractUpToSlot("/shelf=1/slot=13/port=3")); // Output: "/shelf=1/slot=13"
console.log(extractUpToSlot("/shelf=1/slot=142/subslot=2/port=4")); // Output: "/shelf=1/slot=142"

Python Implementation

If you’re working in Python, the logic is nearly identical:

import re

def extract_up_to_slot(path):
    match = re.match(r'^.*\/slot=\d+', path)
    return match.group(0) if match else path

// Test cases
print(extract_up_to_slot("/rack=1/shelf=1/slot=12/port=200"))
print(extract_up_to_slot("/shelf=1/slot=13/port=3"))
print(extract_up_to_slot("/shelf=1/slot=142/subslot=2/port=4"))

Key Benefits

  • Universal: Works with any path structure as long as a /slot=X segment exists (whether there’s a rack before it, subslot after it, etc.).
  • Robust: Handles slot numbers of any length (1-digit, 3-digit, etc.) without adjustments.
  • Clean: Eliminates messy position calculations that break when input formats change.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:07:37