You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google Sheets中使用URI.js去除URL查询参数报错求助

Fixing "TypeError: undefined is not a valid argument for URI" in Google Sheets with URI.js

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_without isn'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:

  1. 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.

  2. 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 has http://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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:33:47