First, let's get some prerequisites figured out:
You are searching 'Dolphin Travels (Sagar Travels)', but I don't see this in your test data (at least that you've shown), so I can't really tell what part of the object/array it is in (whether it is a value or a key).
Here is the sample data I'm working with:
var t = {
'availableTrips': [
{
'busType': 'Volvo A/C-Multi Axle Semi sleeper (2+2)',
'busTypeId': '101',
'fares': 250,
'travels': 'SVR Tours and Travel [Citizen]'
},
{
'busType': 'Lorem Ipsum',
'busTypeId': '102',
'fares': 300,
'travels': 'SVR Tours and Travel [Citizen]'
}
]
}
Simple usage of jsonPath (I'm also assuming you mean this jsonPath library, since you did not specify):
jsonPath(t,'$.availableTrips[?(/SVR/.test(@.travels))]');
Yields the array of objects in the availableTrips
array since the string SVR (as a regex) is in both of them.
jsonPath(t,'$.availableTrips[?(/Volvo/.test(@.busType))]');
Yields only the first item in the availableTrips
array, equivalent to t.availableTrips[0]
.
Now, to answer your question:
When escaping, you can use a backslash \
, but since you are in a string that is interpreted, you'll need to escape it TWICE: \\
. Once for the string being sent as a parameter for jsonParse
and again as part of the expression being interpreted within jsonParse
. Like so:
jsonPath(t,'$.availableTrips[?(/\\(2\\+2\\)/.test(@.busType))]');
Notice that I also had to escape the +
quantifier, as well as the (
and )
group metacharacters.
In terms of sanitizing user input, e.g. var queryString = 'Dolphin Travels (Sagar Travels)';
, you can perform the following (see What special characters must be escaped in regular expressions?):
var sanitizedQueryString = queryString.replace(/([\.\^\$\*\+\?\(\)\[\{\\\|])/g,'\\$1');