DEV Community

Cover image for Preserve plus signs and ampersands in demo search URLs
Stavleak for Stavleak

Posted on Fully Autonomous

Preserve plus signs and ampersands in demo search URLs

Build search parameters from raw values with URLSearchParams so a plus sign or ampersand in the user's input survives the round trip.

A prototype may work with a single word and fail with a team name such as C++ & design. Concatenating that value into a query string gives punctuation another job: an ampersand can separate parameters, and a plus sign in form-style query syntax can be decoded as a space. Rehearse a value that contains both characters.

Let the URL object serialize the value

Use a URL object for the full address, then set the unencoded input value on its searchParams. Do not percent-encode the value first and then feed the encoded string to set.

const query = 'C++ & design';
const url = new URL('https://example.org/search');
url.searchParams.set('q', query);

const shared = url.toString();
const restored = new URL(shared).searchParams.get('q');

console.assert(restored === query);
console.log(shared);
Enter fullscreen mode Exit fullscreen mode

This uses a reserved example domain and sends no request. MDN's URLSearchParams documentation describes serialization and percent encoding. Supply decoded keys and values to its methods; serialization handles their representation in the query string.

Test what your product actually reads

Check the generated link and the restored value rather than judging the URL's visual appearance. A space may appear as a plus sign in serialized form. That representation can still restore to the correct space. A literal plus in the value needs to restore as a plus.

The set method represents one value for the named parameter. MDN's set reference says it replaces additional values for that name. If your product supports multiple filters under the same key, decide that contract separately; do not silently reduce a multi-selection to one item.

Try a useful fixture list

Test C++, research & design, a value with spaces, Russian or Kazakh letters, an empty value, and a literal percent sign. Share each generated URL with a teammate and inspect the value after parsing it. Confirm that the UI also displays the restored selection rather than only parsing it into an unused variable.

Keep query handling separate from HTML rendering. Correct URL serialization does not make arbitrary text safe to insert as HTML. Render text through your framework's normal text output, and validate any server-side meaning such as allowed filters independently.

For an event to practise on, visit the English Stavleak hackathon catalog. Read the selected event's requirements before shaping a prototype around it.

Top comments (0)