RegExp vcf in Javascript

627 Views Asked by At

I have this structure, and i want to extract only FN and TEL:

BEGIN:VCARD
VERSION:2.1
N:Pepe;Perez;;;
FN:Pepe Perez
TEL;HOME:+549465738283
END:VCARD
BEGIN:VCARD
VERSION:2.1
N:Jose;Perez;;;
FN:Jose Perez
TEL;CELL:+549465738284
END:VCARD

Like:

[
    {name: 'Pepe perez', tel: '+549465738283'},
    {name: 'Jose perez', tel: '+549465738284'}
]

I have this code:

var file = fs.readFileSync('app/vcards/00003.vcf', 'utf-8');

var p = new RegExp(/(^FN:)(.*)(\n)(TEL;)(.*:)(\+)([0-9]+)/g);

console.log(p.exec(file));

But result is null

Anybody help me?

2

There are 2 best solutions below

2
On BEST ANSWER

It's not really regex, but on request here's a way to manually parse vCard, as I believe that's the easiest to keep track of and modify

var file = fs.readFileSync('app/vcards/00003.vcf', 'utf-8');
var arr  = [];
var obj  = {};

file.split("\n").forEach(function(line) {
    if ( line.indexOf('FN') === 0 ) {
        obj.name = line.split(':').pop().trim();
    } else if ( line.indexOf('TEL') === 0 ) {
        obj.tel = line.replace(/[^0-9+]/g,'');
        arr.push(obj);
    } else if ( line.indexOf('END') === 0 ) {
        obj = {};
    }
});

var file = document.getElementById('test').innerHTML.trim();
var arr  = [];
var obj  = {};

file.split("\n").forEach(function(line) {
    if ( line.indexOf('FN') === 0 ) {
        obj.name = line.split(':').pop().trim();
    } else if ( line.indexOf('TEL') === 0 ) {
        obj.tel = line.replace(/[^0-9+]/g,'');
        arr.push(obj);
    } else if ( line.indexOf('END') === 0 ) {
        obj = {};
    }
});

document.body.innerHTML = '<pre>' + JSON.stringify(arr, null, 4) + '</pre>';
<div id="test">
BEGIN:VCARD
VERSION:2.1
N:Pepe;Perez;;;
FN:Pepe Perez
TEL;HOME:+549465738283
END:VCARD
BEGIN:VCARD
VERSION:2.1
N:Jose;Perez;;;
FN:Jose Perez
TEL;CELL:+549465738284
END:VCARD
</div>    
    

It should also be noted that there is middleware available for this as well

https://www.npmjs.com/package/vcard

it does basically the same thing, splits the lines and looks for BEGIN and END to get each card etc.

0
On

Use m as the flag for multi-line instead of using g for global. The latter is more useful when doing multiple replacements but doesn't help when you are matching against multiple lines of text.