简体   繁体   中英

Strange result or am I wrong?

I have the following string [row element="div"]This is a row[/row] and I like to extract fromt this string the div property and the string This is a row by using JavaScript and Regex.

The way I am trying to perform this action is the following:

var string = '[row element="div"]This is a row[/row]';
var $d     = string.match(/\[row element="([^"]+)"\](.*?)\[\/row\]/g);

console.log($d);

and the result is:

[row element="div"]This is a row[/row]

So, the question is, am I doing it wrong, or the code behaves strange ?

If this is wrong, how can I extract that parts needed from the string variable ?

The problem is that /g and .match are not compatible with subpatterns.

Instead, try the other way around:

var regex = /......../g;
var $d = regex.exec(string);

console.log($d);

The result should be an array, containing the entire match at index 0, the first subpattern as 1, and the second at 2.

You can call .exec repeatedly to see if there are any more [row element="foo"]bar[/row] patterns matching. .exec will return null if there are no more matches.

You can use:

var $d = string.match(/\[row element="(?:[^"]+)"\](.*?)\[\/row\]/)[1];
//=> "This is a row"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM