How to trim white space in search terms?

I came across the same problem.
In my opinion, this should be the default search behavior in WP.

The solution is to filter the array of parsed query variables.
See the documentation here.

Add this to the functions.php file in your theme directory.

add_filter('request', function ($query_vars) {
    if (!is_admin() && !empty($query_vars['s'])) {
        $query_vars['s'] = trim($query_vars['s']);
    }

    return $query_vars;
});