ECMAScript proposal and specification for String.prototype.remove{Prefix,Suffix}
.
Author(s): @hyperupcall
Champion(s): TBD
Stage: 0
The lack of a built-in way to remove a prefix substring or a suffix substring from a string is an inconvenience and incompleteness of JavaScript. Removing prefix and suffix substrings is a common string manipulation operation and excluding this from ECMAScript means program authors must always write their own implementation or be left with verbose or slower alternatives. Fixing this paper-cut will bring JavaScript more in line with the conveniences of other modern-day languages.
Without native methods, this functionality is often written on-the-fly. For example, to remove a prefix substring, the target string is checked if it startsWith
that substring. If so, a .slice()
is performed on the string, effectively removing the substring; otherwise, the target string is used. Even when using the ternary conditional operator, this is verbose code that either requires assigning the substring to a variable, or duplicating the substring string literal twice.
// removePrefix
const str = 'greninja'
const substr = 'gre'
if (str.startsWith(substr)) {
result = str.slice(substr.length)
// => ninja
}
// removeSuffix
let str = 'charizard'
let substr = 'izard'
let result = str.endsWith(substr) ? str.slice(0, str.length - substr.length) : result
result
// => char
Another common alternative is the use of regular expressions. Although the code is shorter, it is more cryptic (requires knowledge of regular expressions) and has suboptimal performance.
let str = 'mudkip'
str.replace(/kip$/, '')
// => mud
In both alternatives, the semantics aren't always obvious. Other popular languages have realized this and have implemented a built-in method to resolve this.
We propose adding String.prototype.removePrefix
and String.prototype.removeSuffix
to the String prototype.
'greninja'.removePrefix('gre')
// => ninja
'charizard'.removeSuffix('izard')
// => char
The proposed signatures are:
String.prototype.removePrefix(prefix: string): string
String.prototype.removeSuffix(suffix: string): string
- Python (since v3.9) has
.removeprefix
and.removesuffix
- Ruby (since v2.5) has
.delete_prefix
and.delete_suffix
- Rust (since v1.45.0) has
.strip_prefix
and.strip_suffix
- Go (since v1.1) has
strings.TrimPrefix
andstrings.TrimSuffix
The naming parallels Python's .remove{prefix,suffix}
function. A quick peruse of Mootools and Sugar revealed no obvious naming collisions.