2

Trying to parse the following text:

This is one of the [name]John's[/name] first tutorials.

or

Please invite [name]Steven[/name] to the meeting.

What I need is to do a regexp in Javascript to get the name. Doing var str = body.match(/[name](.*?)[\/name]/g); works, but how do I get just the inside of it?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
alexeypro
  • 3,633
  • 7
  • 36
  • 49

4 Answers4

5

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"]
maerics
  • 151,642
  • 46
  • 269
  • 291
3

You want to access the matched groups. For an explanation, see here: How do you access the matched groups in a JavaScript regular expression?

Community
  • 1
  • 1
markijbema
  • 3,985
  • 20
  • 32
3

You made a mistake in your regexp, you have to escape brackets: \[name\]. Just writing [name] in regexp means that there should be either 'n' or 'a' or 'm' or 'e'. And in your case you just want to tell that you look for something started with '[name]' as string

altogether:

/\[name\](.*?)\[\/name\]/g.exec('Please invite [name]Steven[/name] to the meeting.');
console.info( RegExp.$1 ) // "Steven"
Maxym
  • 11,836
  • 3
  • 44
  • 48
0

You can use RegExp.$1, RegExp.$2, all the way to RegExp.$9 to access the part(s) inside the parenthesis. In this case, RegExp.$1 would contain the text in between the [name] and [/name].

Peter C
  • 6,219
  • 1
  • 25
  • 37
  • 1
    No, it is necessary. If he has multiple `[name]...[/name]` tags, doing `(.*)` will do a greedy match and match everything between the first `[name]` and last `[/name]`. – CanSpice Mar 07 '11 at 19:07