egg_server/utils/string.ts

34 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 从小米链接中提取 sheetToken 和 range。
*
* @param {string} url - 要提取数据的URL。
* @returns {{sheetToken: string, range: string} | null} - 包含 sheetToken 和 range 的对象,如果没有匹配则返回 null。
*/
export const extractSheetIds = (url: string) => {
// 定义匹配 wiki 和 sheets 两种URL格式的正则表达式
const pattern =
/wiki\/([\w\d]+)\?sheet=([\w\d]+)|sheets\/([\w\d]+)\?sheet=([\w\d]+)/
const match = url.match(pattern)
if (match) {
return {
sheetToken: match[1] || match[3], // 对于第一种URL格式sheetToken 在组1对于第二种格式在组3
range: match[2] || match[4], // range 在第一种URL格式中是组2在第二种格式是组4
}
}
return null // 如果没有匹配,则返回 null
}
/**
* 校验链接是否合法
* @param {string} link - 网页链接
* @throws {Error} - 当链接为空或格式不正确时抛出错误
*/
export const validateLink = (link: string): void => {
if (!link) throw new Error("链接不能为空")
try {
new URL(link)
} catch {
throw new Error("链接格式不正确")
}
}