Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a separate search string using regex in javascript?

For a search string like ""foo and bar" or foo", i want to separate string in : 1)"foo and bar" 2)or 3)foo. That means I want to consider the quoted words in a single string. In server side i'm using (Java):

Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(searchText);
        while (m.find()) {
            String searchTermStr = m.group(1);
            list.add(buildSearchTerm(searchTermStr));
}

How can a get similiar output in javascript? I'm trying to split the searchText using this regEx and it's not giving the desired result.

var pattern = new RegExp("([^\"]\\S*|\".+?\")\\s*","gi");
var searchTerms = $scope.searchText.split(pattern);
like image 214
fatCop Avatar asked Nov 26 '25 17:11

fatCop


1 Answers

In Javascript you can use this:

var pattern = /([^"\s]+|"[^"]*")/g;

RegEx Demo

You must use String#match in Javascript instead of split:

var searchTerms = $scope.searchText.match(pattern);
//=> ["foo and bar", or, foo]
like image 91
anubhava Avatar answered Nov 29 '25 08:11

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!