Last active
December 29, 2018 00:58
-
-
Save etienne-martin/0c1c45ffcb28497d5688129d59a50d4e to your computer and use it in GitHub Desktop.
String templating
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
interface FormattedMessageProps { | |
message: string, | |
values?: { [key: string]: any; }; | |
} | |
export const formatMessage = ({ message, values = {} }: FormattedMessageProps) => { | |
const chunks = message.split(/({[^}]+})/g); | |
const formattedMessage = chunks.map(chunk => { | |
if (chunk.startsWith("{") && chunk.endsWith("}")) { | |
const key = chunk.slice(1,-1); | |
if (values.hasOwnProperty(key)) { | |
return values[key]; | |
} | |
} | |
return chunk; | |
}); | |
return formattedMessage.join(""); | |
}; | |
export const FormattedMessage = ({ message, values = {} }: FormattedMessageProps) => { | |
const chunks = message.split(/({[^}]+})/g); | |
const formattedMessage = chunks.map((chunk, index) => { | |
if (chunk.startsWith("{") && chunk.endsWith("}")) { | |
const key = chunk.slice(1,-1); | |
if (values.hasOwnProperty(key)) { | |
return <React.Fragment key={index}>{values[key]}</React.Fragment>; | |
} | |
} | |
return <React.Fragment key={index}>{chunk}</React.Fragment>; | |
}); | |
return <>{formattedMessage}</>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment