Javascript question

Associate
Joined
27 Jan 2005
Posts
1,373
Location
S. Yorks
Hi,

I need to check a string for special chars, typically ' " & % this is to be used in an odata query so far I have:

Code:
  if (ProjName.indexOf("&") > 0)
    {
      oDataEndpointUrl += "orb_objectrelationshipSet?$select=orb_accountid,orb_name,orb_objectrelationshipId&$filter=orb_name eq '" + ProjName.replace(/\x26/,"%26")+ "' ";
    }
    else
    {
         oDataEndpointUrl += "orb_objectrelationshipSet?$select=orb_accountid,orb_name,orb_objectrelationshipId&$filter=orb_name eq '" + ProjName + "' ";
    }

But what's an accepted way to check for all of the special chars and replace?

regards,

Matt
 
If you want to url encode some values, you can use encodeURIComponent():

Code:
oDataEndpointUrl += "orb_objectrelationshipSet?$select=orb_accountid,orb_name,orb_objectrelationshipId&$filter=orb_name eq '" + encodeURIComponent(ProjName) + "' ";

That function will encode URL-sensitive characters into their respective entities. For example it would turn '&55%' in to '%2655%25'
 
Last edited:
Thanks for the response.

It works apart from the ' character

Code:
http://A_Server.svc/orb_objectrelationshipSet?$select=orb_accountid,orb_name,orb_objectrelationshipId&$filter=orb_name eq 'Enquiry%2005%2F08%2F14%20Fulham%20(709709)%20-%20O[B]'[/B]Keefe%20Construction'

Why doesn't it convert the ' char?

Matt
 
That's because the apostrophe is a valid character in a URL, if you need that removing too you can use replace() or a regex as needed.

Here's which characters are allowed in a URL:

In general URIs as defined by RFC 3986 (see Section 2: Characters) may contain any of the following characters:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=.

Any other character needs to be encoded with the percent-encoding (%hh). Each part of the URI has further restrictions about what characters need to be represented by an percent-encoded word.

http://stackoverflow.com/questions/1547899/which-characters-make-a-url-invalid
 
So use something like:

Code:
ctrelationshipSet?$select=orb_accountid,orb_name,orb_objectrelationshipId&$filter=orb_name eq '" + encodeURIComponent(ProjName.replace(/\x27/,"%27")) + "' ";

Am new to the javascript - well dip in and out as the job requires...

Matt
 
Hhhhmmm it doesn't like it.

Copying and pasting the url into a browser returns no results, altering the data to some other data without a ' and it returns data.

Any other ideas?

Matt
 
It's possible the %27 isn't being decoded in your server-side code as it's not a normally encoded character. Have you tried it without encoding apostrophes? They shouldn't need changing, in theory.
 
Back
Top Bottom