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?

4 Answers 4

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"]
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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"

Comments

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.