Try using the "exec" method of a regular expression to get the matching groups as an array:
var getName = function(str) {
var m = /\[name\](.*?)\[\/name\]/.exec(str);
return (m) ? m[1] : null;
}
var john = getName("This is one of [name]John's[/name] first tutorials.");
john // => "John's"
var steve = getName("Please invite [name]Steven[/name] to the meeting.");
steve // => "Steven"
This could be easily extended to find all occurrences of names by using a global RegExp:
var getAllNames = function(str) {
var regex = /\[name\](.*?)\[\/name\]/g
, names = []
, match;
while (match = regex.exec(str)) {
names.push(match[1]);
}
return names;
}
var names = getAllNames("Hi [name]John[/name], and [name]Steve[/name]!");
names; // => ["John", "Steve"]