replaceFirstMatch
replaceFirstMatch
(search: regex | string, replacement: string) => (aString: string) => string
Replace the first match of a string or regex.
When passing a regex, make sure the global flag is not set i.e. the regex
/dog/g
will cause an error.const replaceAWithG = replaceFirstMatch('a', 'g') replaceAWithG('aaaaah!') // is 'gaaaah!'
const replaceAWithG = replaceFirstMatch('a', 'g') replaceAWithG('aaaaah!') // is 'gaaaah!'
const replaceAWithG = replaceFirstMatch('a', 'g') replaceAWithG('aaaaah!') // is 'gaaaah!'
const replaceAWithG = replaceFirstMatch('a', 'g') replaceAWithG('aaaaah!') // is 'gaaaah!'
Sometimes we want to replace the first match in text. Below, we are processing weather data from a CSV file. Our boss wants us to show the low and high columns with a symbol '<-->' to convey a range. Since low and high are the initial columns, let's replace the first comma with that symbol.
const csv = `low,high,precipitation% 72,84,0 70,85,15 62,74,40` const conveyLowToHigh = replaceFirstMatch(',', ' <--> ') const updateCSV = compose([ split('\n'), mapValues(conveyLowToHigh), joinValues('\n'), ]) const updatedCSV = updateCSV(csv) console.log(updatedCSV) // prints // low <--> high,precipitation% // 72 <--> 84,0 // 70 <--> 85,15 // 62 <--> 74,40
const csv = `low,high,precipitation% 72,84,0 70,85,15 62,74,40` const conveyLowToHigh = replaceFirstMatch(',', ' <--> ') const updateCSV = compose([ split('\n'), mapValues(conveyLowToHigh), joinValues('\n'), ]) const updatedCSV = updateCSV(csv) console.log(updatedCSV) // prints // low <--> high,precipitation% // 72 <--> 84,0 // 70 <--> 85,15 // 62 <--> 74,40
const csv = `low,high,precipitation% 72,84,0 70,85,15 62,74,40` const conveyLowToHigh = replaceFirstMatch( ',', ' <--> ' ) const updateCSV = compose([ split('\n'), mapValues(conveyLowToHigh), joinValues('\n'), ]) const updatedCSV = updateCSV(csv) console.log(updatedCSV) // prints // low <--> high,precipitation% // 72 <--> 84,0 // 70 <--> 85,15 // 62 <--> 74,40
const csv = `low,high,precipitation% 72,84,0 70,85,15 62,74,40` const conveyLowToHigh = replaceFirstMatch( ',', ' <--> ' ) const updateCSV = compose([ split('\n'), mapValues(conveyLowToHigh), joinValues('\n'), ]) const updatedCSV = updateCSV(csv) console.log(updatedCSV) // prints // low <--> high,precipitation% // 72 <--> 84,0 // 70 <--> 85,15 // 62 <--> 74,40