在Google Sheets中使用URI.js去除URL查询参数报错求助
Hey there, let's break down what's causing this error and how to fix it for your url_without function.
Why You're Seeing This Error
The "undefined is not a valid argument for URI" error pops up because the value you're passing to URI(url) is undefined. This usually happens for a few reasons:
- You're referencing an empty cell in your sheet, so the function receives no input value.
- The parameter passed to
url_withoutisn't a valid string (like a blank cell, number, or malformed data). - There's a mistake in how you're calling the function in the sheet (e.g., missing a cell reference).
Step-by-Step Fix
Here's how to adjust your url_without function to handle edge cases and avoid the error:
Add Input Validation
First, check if the input URL is valid (not empty, and is a string) before passing it to URI.js. This stops undefined values from reaching the URI constructor.Wrap in a Try-Catch Block
Even with validation, malformed URLs might cause errors—using try-catch ensures your function doesn't crash and returns a helpful message instead.
Here's the revised function code:
function url_without(url) { // Handle empty or invalid input first if (!url || typeof url !== 'string') { return ""; // Or return "Invalid URL" for clearer feedback } try { // Initialize URI with the valid URL string const uri = new URI(url); // Clear the query parameters uri.search(""); // Return the cleaned URL return uri.toString(); } catch (error) { // Catch any invalid URL errors and return a message return `Error: ${error.message}`; } }
Additional Checks
- Verify URI.js is Loaded: Make sure you've properly added the URI.js library to your Google Sheets script project. Go to Resources > Libraries in the script editor, and add the URI.js project ID (you can find this in the official URI.js documentation for Google Apps Script integration).
- Test with Valid URLs: When testing the function in your sheet, use cells that contain full, valid URLs (e.g.,
=url_without(A1)where A1 hashttp://test.com/file.php?this=1&that=2).
Example Usage
If cell A1 contains http://test.com/file.php?this=1&that=2, calling =url_without(A1) will return http://test.com/file.php as expected.
内容的提问来源于stack exchange,提问作者Uniextra

