Skip to content

Instantly share code, notes, and snippets.

@crshmk
Last active January 2, 2023 05:35
Show Gist options
  • Save crshmk/6f89628131f1a1aa6c599a0865017aa9 to your computer and use it in GitHub Desktop.
Save crshmk/6f89628131f1a1aa6c599a0865017aa9 to your computer and use it in GitHub Desktop.
a string replace api that takes a map of replacements
const replace = replacements => str => {
const fragmentsToReplace = Object.keys(replacements).join('|')
const regex = new RegExp(fragmentsToReplace, 'g')
return str.replace(regex, match => replacements[match])
}
@crshmk
Copy link
Author

crshmk commented Jun 16, 2021

String.prototype.replace can take a function to map any number of replacements

@crshmk
Copy link
Author

crshmk commented Jan 2, 2023

simple example

import replace from 'replace'

const intReplacements = {
  'one': '1',
  'two': '2'
  }
  
const replaceInts = replace(intReplacements)
  
replaceInts('oneandtwo')
// '1and2'

@crshmk
Copy link
Author

crshmk commented Jan 2, 2023

point free example

import replace from 'replace'
import { 
  join, 
  map,
  pipe, 
  split
 } from 'ramda'

const ucFirst = x => 
  x.charAt(0).toUpperCase() + x.slice(1)

const idReplacements = {
  Api: 'API',
  By: 'by',
  And: 'and',
  'Key Value': 'Key-Value'
 }

const makeTitleFromId = pipe(
  split('-'),
  map(ucFirst),
  join(' '),
  replace(idReplacements)
)

const makeTitlesFromIds = map(makeTitleFromId)

export default makeTitlesFromIds

create labels from DOM ids

import makeTitlesFromIds from './makeTitlesFromIds'

const ids = [
  'api-endpoints',
  'some-section',
  'books-by-user',
  'this-and-that',
  'a-key-value-store'
]

makeTitlesFromIds(ids)
/*
[
  'API Endpoints', 
  'Some Section', 
  'Books by User', 
  'This and That', 
  'A Key-Value Store'
]
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment