Amila Iddamalgoda
Amila Iddamalgoda

Reputation: 4286

Split array by regular expression in Node.js

I'm using https://github.com/joyent/node-strsplit to split the text extracted from a file. I need to extract the data between double curly braces. Following will be some sample text in the file.

I am living in {{address||address of current property owner}} under the name {{name}} and my id (nic) will be {{nic||National Identity Number}})

Here, I want to extract the text inside double opening and closing curly braces. For example the ultimate array should be like, ['address||address of current property owner','name','nic||National Identity Number']

For this, I tried to use the following Regex patterns,

/{{(.*?)}}/
/{{([^}]*)}}/
/\{{([^}]+)\}}/

Following will my code.

var pattern = '/{{(.*?)}}/';
var arr=strsplit(sample_text, pattern);

Please help me out for finalizing the approach. Cheers !!

Updated:

var results = [], re = /{{([^}]+)}}/g, text;

  while(item = re.exec(text)) {
       results.push(item[1]);
  }

Upvotes: 0

Views: 95

Answers (1)

nicael
nicael

Reputation: 18995

You could do it with match() and strip the brackets:

var str = "I am living in {{address||address of current property owner}} under the name {{name}} and my id (nic) will be {{nic||National Identity Number}})";
var result = str.match(/{{.*?}}/g).map(function(x){return x.slice(2,-2)});
console.log(result)

Upvotes: 1

Related Questions