Special character & not working with SharePoint REST API

If you are facing errors using special characters like '&' or '#' while working with SharePoint REST API, we have a quick fix for you. This issue is not related to SharePoint, but can occur with any REST API, say Jira or Graph API.

Special characters must be encoded before using in the URL.

Consider an example, where you are fetching a SharePoint List Item with title = "Sales & Marketing". You will receive a Microsoft.SharePoint.Client.InvalidClientQueryException error - The expression "Title eq 'sales " is not valid."

https://code2care.sharepoint.com/sites/JiraProjects/_api/web/lists/getByTitle('ActionTracker')/items?$filter=Title eq 'Sales & Marketing'&$select=Title

This is because & is a special and reserved character, you need to encode it and pass the encoded value instead.

FIX ==> In the REST Url, replace & (ampersand) with %26.

_api/web/lists/getByTitle('ActionTracker')/items?$filter=Title eq 'Sales %26 Marketing'&$select=Title

⭐ Different scripting languages treat special characters differently, accordingly you may also need to declare the ampersand using one of these - %26, & amp (without space), & amp; (without space), \&, &&, %26amp;.

⭐ In your code, try using encodeURI('Sales & Marketing') or encodeURIComponent('Sales & Marketing') with variables for escaping.

⭐ Another simple solution would be educate users to use 'and' in place of &, like 'Sales and Marketing'.

⭐ There are plenty of character encoder-decoder available online, convert the special character to encoded value and use it in the REST call.

⭐ Tip - # (hash) is another commonly used character, replace it with %23.


Have Questions? Post them here!

Top Hashtags: