Filter a string using Javascript

Filtering a string in Javascript could have been straightforward but unfortunately it is not.

"this_is_it".filter(c -> c != '_')

This code will throw the following exception

Uncaught TypeError: "this_is_it".filter is not a function
    at <anonymous>:1:14

We can transform the string as a char array like this

"this_is_it".split('').filter(c => c != '_').join('')

But there is a funnier way of doing but you should be aware of the pros and cons of this methods:

There is a good chance you will never need to do something like this. Don’t optimise prematurely

[].filter.call("this_is_it", c => c != '_').join('')

Let’s deconstruct this complicated call:

We can apply the filter function on the string by looking at its polyfill: the only feature used is stringVar[index] which exist for string.

Voilà.