2

I have the following code:

var requestUri = webAbsUrl + "/_api/web/Lists/getByTitle('Staff Directory')/Items?$\
        filter=Title eq '" + currentUserEmail + "'&$\
        select=*";

It works until it encountered an employee with an apostrophe in the last name. I tried encodeURI() and encodeURIComponent() but neither worked. I tried searching online and can't seem to find a quick solution.

Example Email: John.O'Doe@domain.com

6

Use below:

var str = fixedEncodeURIComponent(currentUserEmail);

var requestUri = webAbsUrl + "/_api/web/Lists/getByTitle('Staff Directory')/Items?$\
    filter=Title eq '" + str + "'&$\
    select=*";


function fixedEncodeURIComponent(src) {
return encodeURIComponent(src).replace(/[']/g, function (c) {
        return '%' + c.charCodeAt(0).toString(16) + '%' + c.charCodeAt(0).toString(16);
    });
}

Basically, it duplicates the ' twice, and enconde each ' => %27. As a result, the url will show %27%27 per each '

| improve this answer | |
  • does it mean I have to replace a single apostrophe with double apostrophe? I'm confused about how charCodeAt(0).toString(16) = 27? – Tamras Merin May 2 '18 at 19:15
  • I found the answer about .toString(16) here: – Tamras Merin May 2 '18 at 19:25
  • Thanks mate. %27%27 fixed it – Anand Mar 10 at 15:32
4

Deepmala's answer will work, but it seems overly complex and hides both the approach and the actual solution. What you're trying to do is replace a single apostrophe with two, but they both have to be URI-encoded.

A simpler and easier-to-understand solution:

function fixedEncodeURIComponent(src) {
    return encodeURIComponent(src).replace(/[']/g, '%27%27');
}
| improve this answer | |
0

Based on @Deepmala, @Dave Read, and this sharepoint article over here, here is a method that ensures your string is going to follow the Sharepoint REST url format, encoding any apostrophe, or other reserved character:

const encodeRestUrl(query: string) {
    query = encodeURIComponent(query.replace(/[%]/g, '%25'))
      .replace(/[']/g, '%27%27')
      .replace(/[&]/g, '%26')
      .replace(/[#]/g, '%23')
      .replace(/[?]/g, '%3F')
      .replace(/[/]/g, '%2F')
      .replace(/[+]/g, '%2B');
    return query;
  }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.