A search for C++ should not arrive as C followed by two spaces. If it does, inspect how the query was built before changing the search engine. A literal plus sign and an encoded plus sign take different paths through form-style query parsing.
The string constructor parses; append accepts a value
The WHATWG URL Standard defines form-style parsing: raw + becomes a space before percent decoding. Consequently, %2B becomes a literal plus, not a space.
Run these examples in a browser console:
new URLSearchParams(
'q=C++'
).get('q');
// "C " — two trailing spaces
new URLSearchParams(
'q=C%2B%2B'
).get('q');
// "C++"
When building a query from user input, pass the value to append rather than interpolating it into query syntax:
const query =
new URLSearchParams();
query.append('q', 'C++ & Rust');
query.toString();
// "q=C%2B%2B+%26+Rust"
new URLSearchParams(
query.toString()
).get('q');
// "C++ & Rust"
The same approach preserves the ampersand as data instead of introducing another parameter. Give append the original value, not a pre-encoded one: passing C%2B%2B produces q=C%252B%252B.
A percent decoder answers a different question
JavaScript’s decodeURIComponent algorithm decodes percent escapes; it does not apply the form parser’s plus-to-space rule.
decodeURIComponent('C++');
// "C++"
decodeURIComponent('C%2B%2B');
// "C++"
A component decoder and a query parser can therefore disagree without either being broken. Do not run decodeURIComponent again on a value already returned by URLSearchParams: a literal %2B in that value would become + on the second pass. Decode according to the format at each boundary, not until the text looks familiar.
Keep the raw query beside the parsed value
For an incoming full URL, use new URL(address).searchParams. During debugging, keep new URL(address).search too. Comparing the raw query with the parsed value tells you whether a plus arrived literally or as %2B.
URLSearchParams serialization writes spaces as +. A changed query string is not, by itself, proof of changed data. In the round-trip example above, compare the returned value with C++ & Rust, not the serialized query with the original input.
