J3Y
J3Y

Reputation: 1853

User customizable regex expression for string formatting

We have a web-app that allows clients to import some CSV data into our database, e.g. a list of products they sell.

The problem is, we'd like to store their data as-is but let the user specify a custom expression so that when they view the data it looks a bit nicer.

Some imported data might look like this:

product_label,quantity
A: Product1- 001,50
A: Product2- 001,80
A: Product3- 001,150
B: Product5- 001,100

In this case, the client might want to strip out the prefix 'A: ' and the suffix ' - 001' in the string 'A: Product1- 001' so that just 'Product1' is displayed.

The problem is, every client seems to have a different string format and desired output format.

I was thinking of providing the ability to specify a regex to format the string purely on the client-side using javascript but I'm not sure how I would use this regex and how to allow them to specify grouping or back-references.

Any suggestions on how to let them specify their own format? e.g. something like:

match_pattern =  ... // input field text (escaped into a regex)
output_pattern = ... // How to let them specify the output from the match results?
display_string = applyFormatting(string, match_pattern, output_pattern);

Upvotes: 2

Views: 58

Answers (1)

Jamie Barker
Jamie Barker

Reputation: 8256

Here's some Regex to split the string up.

// Set the original string
var strOriginal = 'B: Product5- 001,100';

// Settings to specify which parts they want
var bln = [];
bln[0] = true;
bln[1] = true;
bln[2] = false;
bln[3] = false;

// Split the orginal string up
var str = []
str[0] = strOriginal.replace(/([A-Z]\:\s)([A-Za-z0-9]+?)(\-\s[\d]+?)(\,[\d]+)/,'$1');
str[1] = strOriginal.replace(/([A-Z]\:\s)([A-Za-z0-9]+?)(\-\s[\d]+?)(\,[\d]+)/,'$2');
str[2] = strOriginal.replace(/([A-Z]\:\s)([A-Za-z0-9]+?)(\-\s[\d]+?)(\,[\d]+)/,'$3');
str[3] = strOriginal.replace(/([A-Z]\:\s)([A-Za-z0-9]+?)(\-\s[\d]+?)(\,[\d]+)/,'$4');

var strOutput = '';

for (i = 0; i < str.length; i++) { 
    if (bln[i]) {
        strOutput += str[i] + '<br />';  
    }
}

document.getElementById('test').innerHTML = strOutput;
<div id="test"></div>

Upvotes: 1

Related Questions