Skip to content

Instantly share code, notes, and snippets.

@lricoy
Last active March 24, 2016 15:07
Show Gist options
  • Save lricoy/3bdb8d6a3ed4878976b8 to your computer and use it in GitHub Desktop.
Save lricoy/3bdb8d6a3ed4878976b8 to your computer and use it in GitHub Desktop.
Template format to format values like ${value[0:2]}
/**
* Formats a URI using a context and a given RexExp
* The default format is {value[0:20]} and the [0:2] is optional and represent a value.slice(0,2)
* @param {string} URI The URI to be replace
* @param {object} context The given context to work the lookup. e.g: {value: 'MY VALUE TO REPLACE'}
* @param {RegExp} The regex to find the ocurrences on the URI
*/
function formatCustomURI(URI, context, reg) {
URI = URI || '[0:2]\n\n{val[0:2]} \n{valor[0:2]}\n\nlucas\n${}\n$[]';
reg = reg || /\{(.*?)\}/gi;
let m,
val,
sliceRequired,
startValue,
lastValue,
valueToReplace,
mapObj = {};
let matches = URI.match(reg).forEach(function(m){
val = m.replace('{', '').replace('}', ''); //value inside {}
//console.log(val);
sliceRequired = val.indexOf(']') > -1;
if(sliceRequired) {
let initialParam = val.indexOf('['),
lastParam = val.indexOf(']');
startValue = val.slice(initialParam + 1, val.indexOf(':'));
lastValue = val.slice(val.indexOf(':') + 1, lastParam);
val = val.slice(0, initialParam);
}
valueToReplace = context[val];
valueToReplace = sliceRequired && valueToReplace ? valueToReplace.slice(startValue, lastValue) : valueToReplace;
mapObj[val] = valueToReplace;
URI = valueToReplace ? URI.replace(m, valueToReplace) : URI;
});
//console.log(mapObj);
return URI;
};
var fomartedUrl = formatCustomURI(
'http://www4.tjmg.jus.br/juridico/sf/proc_resultado.jsp?tipoPesquisa=1&comrCodigo={id_basico[16:19]}&txtProcesso={id_basico}&listaProcessos={id_basico}&cpfcnpj=&tipoPessoa=X&naturezaProcesso=0&situacaoParte=X&codigoOAB=&tipoOAB=N&ufOAB=MG&tipoConsulta=1&natureza=0&ativoBaixado=X&numero=1&select=1',
{ id_basico: '9333162303003844424' }
);
console.log(fomartedUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment