Regex to encode an URL with special characters

时间:2019-05-31 11:33:31

标签: regex

I need to encode a string that contains special characters such as whitespaces, ' and ".

I don't know how to create a regex.

I've tried many solutions but none of them seem to work.

My final objective is to have a string such as "black cat" encoded like this "black%20cat".

EDIT: Guys I'm working with a specific software called "Axway policy studio" and it has a component where you put in a regex and a string, in the end you get boolean output such as true or false.

1 个答案:

答案 0 :(得分:2)

It sounds more like your trying to encode things to make them more appropriate for a URL, which does not require you to write your own regex in most platforms.

For instance, in Python, there's the function urllib.parse.urlencode which would do this. In Javascript, there's encodeURI and encodeURIComponent.

TL;DR Look up urlencode in and you'll probably find what you need. Don't bother writing regexes for it unless you really need to.

P.S. Most of the urlencoding is just replacing characters with % followed by their ascii hex value (' ' => %20, '!' => %21, ...)