Fire tips tagged “regular expressions

Extracting floats from strings

To get all float values from a sentence, we can first find them with a regular expression and then map over the matches with parseFloat.

// matches all integer or decimal substrings, like “69” or “4.20”
const numbersRegexp = new RegExp(/\d+(\.\d+)?/, 'g')

// finds all numbers matching the expression and transforms them to numbers
const getFloatsFrom = string => string.match(numbersRegexp).map(parseFloat)

getFloatsFrom("Put the 16 cupcakes in the oven (at 180°C) for 1.5 hours.")
// ⇒ [16, 180, 1.5]

Replacing all matches in a string

When replacing a substring in a string, only the first match is replaced. If we want to replace all matches, we need to use a regular expression and tell it to match globally within the string.

// if the first parameter is a string, only the first match is replaced
'Pika pika!'.replace('ka', 'dgey')   // ⇒ 'Pidgey pika!'

// we can write the pattern as a regular expression, which achieves the same
'Pika pika!'.replace(/ka/, 'dgey')   // ⇒ 'Pidgey pika!'

// with the additional `g`-flag, all matches (globally) are replaced
'Pika pika!'.replace(/ka/g, 'dgey')  // ⇒ 'Pidgey pidgey!'

Splitting strings by lengths

JavaScript can split strings at given characters. By matching against a regular expression, we can split strings into substrings of a given length instead.

// split at every `O`; all `O`s are gone in the result
'BRBIDKLOLOMGOK'.split('O')  // ⇒ ['BRBIDKL', 'L', 'MG', 'K']

// split into groups of up to 3 characters (the last group can be shorter)
'BRBIDKLOLOMGOK'.match(/.{1,3}/g)  // ⇒ ['BRB', 'IDK', 'LOL', 'OMG', 'OK']