Skip to content

Instantly share code, notes, and snippets.

@etienne-martin
Last active December 29, 2018 00:58
Show Gist options
  • Save etienne-martin/0c1c45ffcb28497d5688129d59a50d4e to your computer and use it in GitHub Desktop.
Save etienne-martin/0c1c45ffcb28497d5688129d59a50d4e to your computer and use it in GitHub Desktop.
String templating
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