Why JavaScript’s split Can’t Rejoin Strings—and the New splitN Proposal
The recent TC39 meeting promoted the reversible-string-split proposal to Stage 1, outlining the criteria for advancement and introducing a splitN method that makes JavaScript’s string splitting reversible, while comparing it with split implementations in other major languages.
In the recent TC39 meeting, only the reversible-string-split proposal advanced from Stage 0 to Stage 1, while other proposals made no progress.
Stage 0 → Stage 1 Requirements
Find a TC39 champion for the proposal.
Clearly define the problem, need, and rough solution.
Provide examples of the problem and solution.
Discuss API shape, key algorithms, semantics, and implementation risks; note that Stage 1 proposals may undergo significant changes.
Reversible String Split
Link: https://github.com/tc39/proposal-reversible-string-split
JavaScript’s split method takes a separator and an optional limit, but when a limit is set the remaining part of the string is discarded, unlike most other languages where the remainder is kept.
const str = 'a|b|c|d|e';
console.log(str.split("|", 2)); // ["a", "b"]In Java, Rust, Go, and Python the split functions retain the leftover substring after reaching the limit:
// Java example
class Playground {
public static void main(String[] args) {
String s = new String("a|b|c|d|e|f");
for (String val : s.split("\\|", 2)) {
System.out.println(val);
}
}
}
// Output:
// a
// b|c|d|e|f // Rust example
fn main() {
let v = "a|b|c|d|e|f".splitn(2, "|").collect::<Vec<_>>();
println!("{:?}", v);
}
// Output: ["a", "b|c|d|e|f"] // Go example
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Printf("%#v", strings.SplitN("a|b|c|d|e|f", "|", 2))
}
// Output: []string{"a", "b|c|d|e|f"} # Python example
print('a|b|c|d|e|f'.split('|', 2))
# Output: ['a', 'b', 'c|d|e|f']Because JavaScript’s split discards the remainder, the operation is not reversible; the proposal introduces a new splitN method that behaves like other languages, performing N‑1 splits and returning an array of length N that includes the leftover part.
console.log("a|b|c|d|e|f".splitN("|", 2)); // ["a", "b|c|d|e|f"]The historical reason for JavaScript’s current behavior is unclear, but the limit argument first appeared in Netscape Navigator 4 (1997) and was formally recorded in ECMAScript 3.
The JavaScript Chinese Interest Group (JSCIG) invites developers to discuss ECMAScript topics on GitHub: https://github.com/JSCIG/es-discuss/discussions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
