Replacing all matches in a string
The String prototype’s replace function only replaces the first occurrence of a substring by default. We can extend that with a global flag on the expression.
Read fire tipThe constructor for Boolean values is all you need to filter all falsy values from an array. Keep in mind that this takes out false
, 0
, null
, undefined
, empty strings, and NaN
. If you don’t want that, filter by something more specific.
const values = [
5, null, false, 'hi', 0, undefined, { name: 'Tim' }, '', true, NaN, [7]
]
// `Boolean` takes out ALL falsy values
values.filter(Boolean)
// ⇒ [5, 'hi', { name: 'Tim' }, true, [7]]
// `x != null` leaves most falsy values, taking out `null` and `undefined`
values.filter(value => value != null)
// ⇒ [5, false, 'hi', 0, { name: 'Tim' }, '', true, NaN, [7]]
The String prototype’s replace function only replaces the first occurrence of a substring by default. We can extend that with a global flag on the expression.
Read fire tipWith JavaScript’s built-in formatter for relative timestamps, we can build strings like “2 months from now” without having to use third party libraries.
Read fire tip