I’m writing a JavaScript web application. I would like to allow users to search a directory by regex, and write their search term to the URL so they can bookmark the results.
For example, to produce a bookmarkable search for states with names starting “A” and ending “a”:
/states/^A.*a$
People should be able to bookmark this URL and get results matching Alaska, Arizona and Alabama.
However, I’m finding that URL-safe characters and regex characters don’t play nicely together. For example, when I write ^ to the URL, browsers rewrite it as %5E.
Can anyone suggest a better way to create a bookmarkable URL for a regex? I don’t need to support every possible regex character: just ASCII plus $, *, ?, ^, and |.
Ideally I’d like to avoid a long clunky URL with GET parameters like /states?init=A&final=a, but maybe that’s the way I need to go.
If you are really set on having regex searches “persisted” in URLs, I would simply URL-encode / URL-decode the search string and be done with it.
You can explicitly URl-Encode the search string, and then explicitly decode it when they make the request.
That said, I would strongly encourage you to set the search string as a URL query parameter rather than as part of the URL itself. Especially in your case where it’s a search, you are much better off to have the query string as, well, a query string, rather than the URL. It helps things like SEO, REST-compliance, URL maintainability, etc.
Lastly, there are other ways to allow users to bookmark searches as well. If you give each search an ID, and store the actual query in a database for that particular bookmark ID, you can give your users nice urls like
/states/search/bookmark/12345/that are clean, user-friendly, easily bookmarked, shareable, and, best of all, you can do things with them behind the scenes if you need to. This is great for times when you need to upgrade your search, or want to add more power, etc.