如何按逗号分割字符串同时保留所有空格?
Ah, I see the issue—your original regex \\s*,\\s* is consuming the spaces around the comma during the split, which is why those spaces get lost from your array elements. Let's fix that with a couple of straightforward solutions depending on exactly what you need.
Solution 1: Split on the comma alone (preserve all spaces in elements)
If your main goal is to get an array where each element retains its surrounding spaces (like [" hello ", " world "] from the input " hello , world "), simply split on the comma character itself. This way, all spaces before the comma stay attached to the first element, and all spaces after stay with the second:
const input = " hello , world "; const splitArray = input.split(","); // Result: [" hello ", " world "]
This works for any number of spaces (or tabs) around commas—they'll all stay with their respective elements in the array.
Solution 2: Directly get the desired joined string (replace commas with single spaces)
If you ultimately want the output string " hello world " (replacing the comma and its surrounding spaces with a single space, while keeping leading/trailing spaces), a regex replace is more efficient than splitting and joining:
const input = " hello , world "; const output = input.replace(/\s*,\s*/g, " "); // Result: " hello world "
The regex \s*,\s* matches any number of whitespace characters (including zero) before and after a comma, and replaces the entire match with a single space. Perfect for your use case.
Solution 3: Split first, then join while preserving leading/trailing spaces
If you must split first and then reconstruct the string (keeping leading/trailing spaces), you can trim each element, join with a single space, then reattach the original leading and trailing whitespace:
const input = " hello , world "; const trimmedParts = input.split(",").map(part => part.trim()); // Get original leading/trailing spaces const leadingSpaces = input.match(/^\s*/)[0]; const trailingSpaces = input.match(/\s*$/)[0]; // Reconstruct the final string const output = leadingSpaces + trimmedParts.join(" ") + trailingSpaces; // Result: " hello world "
All these approaches handle varying amounts of whitespace around commas, so they'll work even if your input has multiple spaces or tabs instead of just one.
内容的提问来源于stack exchange,提问作者squlerr

