Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a substring surrounded by known prefix and suffix in javascript [closed]

Given a string, such as:

example string with an intended nested string to match.

How to isolate a substring knowing only a prefix and suffix for it, e.g. between intended and to match?

like image 377
Vincent Scheib Avatar asked May 09 '13 22:05

Vincent Scheib


1 Answers

Use regular expressions with non-capturing parentheses, like so:

string = 'example string with an intended nested string to match.';
regexp = /(?:intended)(.*)(?:to match)/;
firstMatch = regexp.exec(string)[1]; // " nested string "

The question mark has several uses in regular expressions, the parentheses question mark colon form (?:more regex) is the non-capturing parentheses.

See MDN for more details of exec(), string.match(), and regular expressions.

like image 182
Vincent Scheib Avatar answered Nov 14 '22 19:11

Vincent Scheib