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:
- 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). - 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. - 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
相关产品推荐
相关产品推荐

