How can a single search string using a regular expression in javascript?
For a search string like "foo and bar" or foo, I want to highlight the string in: 1) "foo and bar" 2) or 3) foo. This means that I want to view the quoted words in one line. On the server side, I am using (Java):
Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(searchText);
while (m.find()) {
String searchTermStr = m.group(1);
list.add(buildSearchTerm(searchTermStr));
}
How can one get similar output in javascript? I am trying to split searchText using this regEx and it doesn’t give the desired result.
var pattern = new RegExp("([^\"]\\S*|\".+?\")\\s*","gi");
var searchTerms = $scope.searchText.split(pattern);
+3
source to share
1 answer
In Javascript, you can use this:
var pattern = /([^"\s]+|"[^"]*")/g;
Demo version of RegEx
You should use String#match
in Javascript instead split
:
var searchTerms = $scope.searchText.match(pattern);
//=> ["foo and bar", or, foo]
+2
source to share