2

In javascript, I've got a block of HTML like this:

<h2>{title}</h2>
<p><a href="{url}">{content}</a></p>

And I'm trying use regex "match" to spit out an array of all the {item}'s. So my output should look like:

['title', 'url', 'content']

I've gotten as far as:

var pattern = new RegExp("\{[a-zA-Z]+\}+");
var match = pattern.exec("{Sample} bob {text}");

But it's only returning the first tag.

This is just beyond my regex skills. Can anyone help?

Cheers!

4

5 回答 5

7

You need to create a pattern with the global flag:

var pattern = new RegExp("\{[a-zA-Z]+\}", "g");

or:

var pattern = /\{[a-zA-Z]+\}/g;

Then you can call the match() method on your string to get a list of matches:

var matches = "{Sample} bob {text}".match(pattern);
于 2008-11-17T17:37:16.507 回答
2

I think you want:

var pattern = new RegExp("\{[a-zA-Z]+\}+", "g");

The second option is a flag telling it to search the entire string and return all matches.

See: http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/ for more details.

于 2008-11-17T17:25:47.667 回答
1

Much as I like to roll my own RegExp (and you really just need the global flag), have you looked at prototype templates, Trimpath JST or anything like that?

Because possibly rolling your own won't be as efficient for reuse as the above examples. EG:

String.prototype.template = function (obj) {
 return this.replace(/{([^{}]+)}/g,
  function (full, word) {
   return((typeof obj[word]==='string'||typeof obj[word]==='number')?obj[word]:full);
  }
 );
};

"The {adj1} {adj2} {noun}.".template({adj1: 'lazy',adj2: 'brown', noun: 'dog'})
==> "The lazy brown dog."

This runs your regex each time, while I believe the prototype templates basically does it once.

于 2008-11-17T17:49:09.587 回答
1

Have you tried this yet?

<script>
var text = '<h2>{title}</h2>\n<p><a href="{url}">{content}</a></p>';
var regex = /\{[a-z]+\}/ig;
var result = text.match(regex);
for (var i = 0; i < result.length; i++) {
    console.debug(i + ". " + result[i]);
}
/*
gives:
0. {title}
1. {test}
2. {url}
3. {content}
*/
</script>
于 2008-11-17T17:58:38.133 回答
0

I got off path by using exec for testing.

于 2008-11-17T17:42:29.473 回答