owl
owl

Reputation: 4501

Javascript regexp match doesn't work

var code = '{html}here is html code{/html}{css}here is css code{/css}';
var preg = code.match(new RegExp(/\{.*?\}(.*?)\{\/.*?\}/g));
console.log(preg[1][0]);

Result: {.

How to output "here is html code" and "here is css code"?

jsfiddle: http://jsfiddle.net/cqr3K/

Upvotes: 0

Views: 273

Answers (3)

Amit Joki
Amit Joki

Reputation: 59292

You can do this:

var code = '{html}here is html code{/html}{css}here is css code{/css}';
var preg = code.replace(/\{.*?\}(.*?)\{\/.*?\}/g, function (match,group) {
    console.log(group);
    return "";
});

Upvotes: 2

hwnd
hwnd

Reputation: 70750

Another way to get all submatches.

var code = '{html}here is html code{/html}{css}here is css code{/css}';
var re   = /[^}]+(?=\{)/g;
var match;

while (match = re.exec(code)) {
   console.log(match[0]);
}

Output

here is html code
here is css code

Upvotes: 2

sshashank124
sshashank124

Reputation: 32207

You can do that as follows:

/\}(.*?)\{/g

The first captured group $1 is what you want. It will contain here is html code and here is css code

Demo: http://regex101.com/r/yC7lD7

Upvotes: 0

Related Questions