alexeypro
alexeypro

Reputation: 3673

JavaScript's regexp

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?

Upvotes: 2

Views: 503

Answers (4)

maerics
maerics

Reputation: 156434

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"]

Upvotes: 5

Peter C
Peter C

Reputation: 6307

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].

Upvotes: 0

Maxym
Maxym

Reputation: 11896

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"

Upvotes: 3

markijbema
markijbema

Reputation: 4055

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

Upvotes: 3

Related Questions