Skip code blocks

This commit is contained in:
Muhsin 2022-12-27 15:48:48 +05:30
parent 9d12826cb0
commit ea5a25934d
2 changed files with 19 additions and 4 deletions

View file

@ -1,12 +1,14 @@
const MESSAGE_VARIABLES_REGEX = /{{(.*?)}}/g;
export const replaceVariablesInMessage = ({ message, variables }) => { export const replaceVariablesInMessage = ({ message, variables }) => {
const regex = /{{(.*?)}}/g; return message.replace(MESSAGE_VARIABLES_REGEX, (match, replace) => {
return message.replace(regex, (match, replace) => {
return variables[replace.trim()] return variables[replace.trim()]
? variables[replace.trim().toLowerCase()] ? variables[replace.trim().toLowerCase()]
: ''; : '';
}); });
}; };
const skipCodeBlocks = str => str.replace(/```(?:.|\n)+?```/g, '');
export const getFirstName = ({ name }) => { export const getFirstName = ({ name }) => {
return name.split(' ')[0]; return name.split(' ')[0];
}; };
@ -42,9 +44,12 @@ export const getMessageVariables = ({ conversation }) => {
}; };
export const getUndefinedVariablesInMessage = ({ message, variables }) => { export const getUndefinedVariablesInMessage = ({ message, variables }) => {
const regex = /{{(.*?)}}/g; const messageWithOutCodeBlocks = skipCodeBlocks(message);
const matches = message.match(regex); const matches = messageWithOutCodeBlocks.match(MESSAGE_VARIABLES_REGEX);
const undefinedVariables = []; const undefinedVariables = [];
if (!matches) {
return [];
}
matches.forEach(match => { matches.forEach(match => {
const variable = match const variable = match
.replace('{{', '') .replace('{{', '')

View file

@ -123,4 +123,14 @@ describe('#getUndefinedVariablesInMessage', () => {
expect.arrayContaining(['{{contact.twitter}}']) expect.arrayContaining(['{{contact.twitter}}'])
); );
}); });
it('skip variables in string with code blocks', () => {
const message =
'hey {{contact_name}} how are you? ``` code: {{contact_name}} ```';
expect(
getUndefinedVariablesInMessage({ message, variables }).length
).toEqual(1);
expect(getUndefinedVariablesInMessage({ message, variables })).toEqual(
expect.arrayContaining(['{{contact_name}}'])
);
});
}); });