3

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);

1 Answer 1

2

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

Comments

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.