Skip to content

Instantly share code, notes, and snippets.

@franciscojsc
Last active July 11, 2021 13:14
Show Gist options
  • Save franciscojsc/58f6e0920aaa0222b505dd7045c286ff to your computer and use it in GitHub Desktop.
Save franciscojsc/58f6e0920aaa0222b505dd7045c286ff to your computer and use it in GitHub Desktop.
Verifique a ocorrência do texto usando Regex
/**
* @description Identificar a ocorrência do texto por meio de Regex
*
* @param {String} text Texto informado pelo usuário
* @param {Object} options Objeto com os pares de chave e valor
*
* @return {String} Retorna a opção selecionada pelo usuário ou o valor padrão
**/
function run(text, options) {
if (typeof options == "string") options = JSON.parse(options);
var match = matchKey(text, options);
return options[match] || options["default"];
}
/**
* @description Verificar se o texto possui correspondência no Regex
*
* @param {String} text
* @param {Object} options
*
* @return {String} Retorna a primeira ocorrência
**/
function matchKey(text, options) {
return Object.keys(options).filter(function(value) {
return text.match(new RegExp(value, "gmi"));
})[0];
}
// Exemplo de uso
// Json
var options1 = '{"oi|ol(á|a)":"Olá","(tch|x)au":"Tchau","Bom dia":"Bom dia :)","Boa tarde":"Boa tarde :)","Boa noite":"Boa noite :)","default":"Não conseguir entender"}';
var result1 = run('oi', options1);
console.log(result1);
// Object
var options2 = {
"oi|ol(á|a)": "Olá",
"(tch|x)au": "Tchau",
"Bom dia": "Bom dia :)",
"Boa tarde": "Boa tarde :)",
"Boa noite": "Boa noite :)",
default: "Não conseguir entender"
};
var result2 = run('Boa tarde', options2);
console.log(result2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment