TypeScript 函数: 判断字符串是否以特定字符串开头或结尾
"使用 TypeScript 编写的函数,用于判断一个字符串是否以某些特定字符串开头或结尾,并返回特定字符串的下标。该函数接收待测字符串、特定字符串数组和是否以开头结尾的布尔值作为参数。\n\ntypescript\nfunction checkString(str: string, specificStrings: string[], isStart: boolean = true): number {\n for (let i = 0; i < specificStrings.length; i++) {\n if (isStart && str.startsWith(specificStrings[i])) {\n return i;\n }\n if (!isStart && str.endsWith(specificStrings[i])) {\n return i;\n }\n }\n return -1; // 如果不符合条件,则返回 -1 表示没有找到特定字符串\n}\n\n\n使用示例:\n\ntypescript\nconst str = \"Hello, World!\"\nconst specificStrings = [\"Hello\", \"Hi\", \"World\"]\n\nconst startIndex = checkString(str, specificStrings, true)\nconsole.log(startIndex); // 输出 0,表示以 \"Hello\" 开头\n\nconst endIndex = checkString(str, specificStrings, false)\nconsole.log(endIndex); // 输出 2,表示以 \"World\" 结尾\n\n\n**注意:**在 TypeScript 中,你需要使用编译器将 TypeScript 代码转换为 JavaScript 代码,然后在浏览器或 Node.js 等环境中运行 JavaScript 代码。\n
原文地址: https://www.cveoy.top/t/topic/pPnq 著作权归作者所有。请勿转载和采集!