Last active
January 2, 2023 05:35
-
-
Save crshmk/6f89628131f1a1aa6c599a0865017aa9 to your computer and use it in GitHub Desktop.
a string replace api that takes a map of replacements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const replace = replacements => str => { | |
const fragmentsToReplace = Object.keys(replacements).join('|') | |
const regex = new RegExp(fragmentsToReplace, 'g') | |
return str.replace(regex, match => replacements[match]) | |
} |
simple example
import replace from 'replace'
const intReplacements = {
'one': '1',
'two': '2'
}
const replaceInts = replace(intReplacements)
replaceInts('oneandtwo')
// '1and2'
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
String.prototype.replace can take a function to map any number of replacements