DEV Community

Discussion on: Some Useful JavaScript String Methods You May Not Know About

Collapse
 
apsillers profile image
Andrew Sillers • Edited

A thorough overview!

I did want to point out that .split does not know how to use an array of strings as separators. Your example works because any object passed as a first argument to .split is converted to a string first. As it happens, the stringified form of [' '] is ' ', so this works, but as soon as you add a second element to the array, you would get very different results -- for example, ['a', 'b'] stringifies to the three-character delimiter 'a,b'.

A few other bug fixes:

  • the chickens-to-ducks example doesn't actually show the replacement in its output
  • the .split example with a regex incorrectly escapes the \d, which isn't necessary in a regex literal (but would be needed in a string argument to the new RegExp constructor)

^ this is actually a very interesting use of a regex split, because normally the sequence captured by the regex is not included in the output array. However, because you use capture-group parentheses in your regex -- (\d) instead of \d -- the capture-group sequence is spliced into the output array.

Collapse
 
aumayeung profile image
John Au-Yeung

Thanks for looking at the examples.

I'll check them later.