DrZ
DrZ

Reputation: 181

Using regex to extract strings given a pattern in JavaScript

I'm trying to figure out how to grab only the values in between known begin and end strings. For example, using this string:

I need [?Count?] [?Widgets?]

I need the the values Count and Widgets returned.

I tried

[?(.*)?]

and ended up with

I need [
Count
] [
Widgets
]

Is there a way, using these begin and end strings, to parse out the values I need? Or should I try and find a way to change them before parsing out the values? I really appreciate any help you can provide.

Thank you!

Upvotes: 0

Views: 738

Answers (2)

Ben Lee
Ben Lee

Reputation: 53309

var str = "I need [?Count?] [?Widgets?]";
$(str.match(/\[\?.*?\?\]/g)).map(function(i) { return this.match(/\[\?(.*)\?\]/)[1] });
// => ['Count'], 'Widgets']

Note that in the regex, you have to escape [, ], and ? as they are special characters. Also use the g flag at the end of the regex to find all matches. I'm also using .*? instead of .* -- that means non-greedy match or "find the shortest possible match", which is what you want here.

Finally, the results are mapped (using jquery map) to remove the '[?' and '?]' from the results.

Or, if you don't want the special characters removed, don't even use the map:

var str = "I need [?Count?] [?Widgets?]";
str.match(/\[\?.*?\?\]/g);
// => ['[?Count?]'], '[?Widgets?]']

Upvotes: 2

verybadbug
verybadbug

Reputation: 929

In your regular expression try \[\?([^\?]*)\?\]

Upvotes: 1

Related Questions