1

I have a little AS3 script to convert all special characters in a string to their character codes.

Here is the script:

url = url.replace(new RegExp("%","g"),"%25")
            .replace(new RegExp("?","g"),"%3F")
            .replace(new RegExp(":","g"),"%3A")
            .replace(new RegExp("/","g"),"%2F")
            .replace(new RegExp("=","g"),"%3D")
            .replace(new RegExp("&","g"),"%26");

Now, I'm not even a beginner with RegExp, but I gave it a try. The little script seems to do the trick quite well, but only the question mark (?) isn't replaced.

Anyone who can tell me why?

If you can also tell me a more short way to code this, feel free to share it, I know this isn't the best practice of RegExp...

greets

1
  • Shorter way would be to use a regular expression literal: .replace(/%/g, "%25"). Note that in this case, the ? would only need one backslash for escaping: /\?/g, because the backslash is not inside a string. There's no other way to replace all occurrences that is shorter, faster or better practice (OK, better practice is debatable). Except if crooksy88's way applies to your case, which I'd say it does. Commented Nov 19, 2012 at 22:32

2 Answers 2

3

You have to escape the question mark: "\?"

Sign up to request clarification or add additional context in comments.

2 Comments

... with an additional backslash: "\\?". The first one to escape the second one, the second one to escape the '?' in the regular expression.
@TheKaneda addiditonal backslash works, but now I'm using the encodeURIComponent() you commented at the other anwer.
2

Not sure if this is of help but do you know about escape?

e.g.

var encodedURL:String = escape(url);

2 Comments

The use case here seems slightly different, since Hans Vn is specifically encoding the URL special characters (specifically the '/', which is not converted by escape()) - likely for use as a URL parameter? In that case, encodeURIComponent() would be closer: var encodedURL:String = encodeURIComponent(url); adobe.ly/URndUU
@TheKaneda: encodeURIComponent() seems to do the trick just fine. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.