esamattis / esamattis/underscore.string

Trim Algorithm Is Overly Simplistic

Open
#151 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
3.4k
Forks
367
PR merge metrics
No merged PRs in 30d

Description

If you try doing `_.trim('someProperty', 'Property')`, you might be surprised at the result: instead of "some" (as you might expect), you get "som".

This happens because the current trim implementation just takes every character in your second arg and throws them inside "[]" in a regex. So if a letter in the second arg (eg. 'e') exists in the part that shouldn't be trimmed, that letter (or letters) get trimmed also. In other words, `_.trim(anyStringWhatsoever, 'a-zA-Z1-0') == ''`.

I think a much less error-prone approach would be to check whether arg #1 `startsWith`/`endsWith` arg #2(or both, depending on whether this is a `trim`/`ltrim`/`rtrim`); if not, just return arg #1. If it does start/end with arg #2, simply use `.substring` to do the trimming:
`ltrim = arg1.substring(arg2.length);`
`rtrim = arg1.substring(0, arg1.length - arg2.length);`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.