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

JavaScript多分隔符字符串拆分:快速解析特定格式字符串

Fast String Parsing in JavaScript for Your Format

Nice one! If you're looking for the fastest way to parse that string into the desired format, regex-based replacement is your best bet—it minimizes the number of passes over the string, which is key for performance (especially if you're processing lots of these strings).

Here's a concise, optimized solution:

const input = "Name01: Name02 - Project Name (Client) - Infos";
const parsedString = input
  // First pass: replace all unwanted separators with spaces
  .replace(/(: | - |[()])/g, ' ')
  // Second pass: collapse any multiple spaces into a single space
  .replace(/\s+/g, ' ')
  // Trim any leading/trailing whitespace (just in case)
  .trim();

console.log(parsedString); // Output: "Name01 Name02 Project Name Client Infos"

How this works:

  1. First replacement: The regex (: | - |[()]) matches all your target separators (: , -, (, )) and replaces each with a single space. This converts the original string into something like "Name01 Name02 Project Name Client Infos" (with double spaces between sections).
  2. Second replacement: \s+ matches one or more whitespace characters, replacing them with a single space to clean up any extra spaces from the first step.
  3. Trim: Ensures there are no leading or trailing spaces in the final output (though your input format probably doesn't have these, it's a safe guard).

Alternative (readable, slightly less performant):

If you prefer a more explicit approach without regex, you can split the string into parts and filter out unwanted elements:

const input = "Name01: Name02 - Project Name (Client) - Infos";
const parsedString = input
  .split(/(: | - |[()])/)
  .filter(part => part.trim() !== '')
  .join(' ');

This splits the string at each separator, removes empty/whitespace-only parts, then joins everything back with spaces. It's easier to follow for some, but the regex replace method is faster for large datasets.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:43:34