How to escape a single quote to be used in an OData query?

Viewed 33288

I am using OData to query my database. The following line of code works fine when “adapterName” just contains text.

ds.query('/DataAdapters?$filter=Name eq \'' + adapterName + '\'', ifmgr_CreateAdapter_Step1, onGenericFailure, '');

If “adapterName” contains a single quote it fails. I tried escaping the single quote by using the following code:

adapterName = adapterName.replace(/\'/g, '\\\'');

Although this correctly escapes the user defined text the function still fails. Can anyone tell me what the correct format is for text in the query?

5 Answers

Actually %27 is not a solution. The correct way to escape is to place two single quotes into the string instead one. In example "o''clock"

It's actually described in oData docs: http://docs.oasis-open.org/odata/odata/v4.01/cs01/part2-url-conventions/odata-v4.01-cs01-part2-url-conventions.html#sec_URLComponents

For example, one of these rules is that single quotes within string literals are represented as two consecutive single quotes.

Example 3: valid OData URLs:

http://host/service/People('O''Neil')

http://host/service/People(%27O%27%27Neil%27)

http://host/service/People%28%27O%27%27Neil%27%29

http://host/service/Categories('Smartphone%2FTablet')

Example 4: invalid OData URLs:

http://host/service/People('O'Neil')

http://host/service/People('O%27Neil')

http://host/service/Categories('Smartphone/Tablet')

The first and second examples are invalid because a single quote in a string > literal must be represented as two consecutive single quotes. The third example is invalid because forward slashes are interpreted as path segment separators and Categories('Smartphone is not a valid OData path segment, nor is Tablet').

Related