antonyboom antonyboom - 2 months ago 21
AngularJS Question

Simplify series of regex-based string replacements

So I'm using

filter
in my angular app. This filter takes a string and coverts it to text. I have a multiple rules in this filter, because each string is a different. Each of this rules I defined step by step, like here:

.filter('filter', function () {

return function (item) {
var space = item.replace(/\./g, " ");
var result = space.replace(/([A-Z])/g, " $1");
var ids = result.replace(/Id==/g, " ");
var categories = ids.replace(/Id=in=\(/g, ' ');
var text = categories.replace(/title==/g, 'title: ');
var desc = text.replace(/description==/g, 'description: ');

var dots = desc.replace(/\*/g, ' ');
var parants = dots.replace(/\)/g, ' ');
var commas = parants.replace(/\,/g, '');

var equal = commas.replace(/=/g, '');
var more = equal.replace(/>/g, '');
var line = more.replace(/-/g, '');
var semidots = line.replace(/:/g, '');

var numbers = semidots.replace(/[0-9]/g, '');

var final = numbers.replace(/Z/g, '');
return final.charAt(0).toUpperCase() + final.slice(1)

}
})


and this is example of string

title==*test*;description==*some%20desciption*;eventTypeId==10;studyId==99999;priorityId==2;severityId==3;occuredDate%3E=2016-09-01T04:00:00.000Z


The final result is good enough and looks like:

example of filter applied

I'm sure this code can be more simple, but I'm not so good in regex, so my question is, how to make this regex rules more simple and beautiful?
I appreciate any help.

This is simple plunker with my example

Answer

Aside from working on complicated regex, one approach you could take is to manage a list of mutations that are applied in sequence.

function filter(item){
   var replacements = [];

   replacements.push([/\./g, " "]);
   replacements.push([/([A-Z])/g, " $1"]);
   replacements.push([/Id==/g, " "]);
   replacements.push([/Id=in=\(/g, ' ']);
   replacements.push([/title==/g, 'title: ']);
   replacements.push([/description==/g, 'description: ']);
   replacements.push([/\*/g, ' ']);
   replacements.push([/\)/g, ' ']);
   replacements.push([/\,/g, '']);
   replacements.push([/=/g, '']);
   replacements.push([/>/g, '']);
   replacements.push([/-/g, '']);
   replacements.push([/:/g, '']);
   replacements.push([/[0-9]/g, '']);
   replacements.push([/Z/g, '']);
   
   for (var x = 0, r = replacements[0]; 
       x < replacements.length; 
       r = replacements[++x])
    item = item.replace(r[0], r[1]);
  
  return item.charAt(0).toUpperCase() + item.slice(1)
}

var items = 'title==*test*;description==*some%20desciption*;eventTypeId==10;studyId==99999;priorityId==2;severityId==3;occuredDate%3E=2016-09-01T04:00:00.000Z'.split(';');

console.log(items.map(filter));

Comments