用正则表达式写个ts函数用于检测是否以特定字符串开头或结尾接受两个参数 分别为特定字符串string和一个bool值开头或结尾
以下是一个用于检测是否以特定字符串开头或结尾的 TypeScript 函数,使用正则表达式:
function checkString(input: string[], isStart: boolean): RegExp {
let pattern = '';
if (isStart) {
pattern = `^(${input.join('|')})`;
} else {
pattern = `(${input.join('|')})$`;
}
return new RegExp(pattern);
}
使用示例:
const strings = ['apple', 'banana', 'cherry'];
const startsWithApple = checkString(strings, true);
const endsWithCherry = checkString(strings, false);
console.log(startsWithApple.test('apple pie')); // true
console.log(startsWithApple.test('banana split')); // false
console.log(endsWithCherry.test('cherry blossom')); // true
console.log(endsWithCherry.test('banana split')); // false
该函数接受两个参数:一个包含特定字符串的数组 input 和一个布尔值 isStart,用于指示是检测开头还是结尾。函数返回一个正则表达式对象,可以使用 test() 方法来检测字符串是否匹配
原文地址: https://www.cveoy.top/t/topic/h5dY 著作权归作者所有。请勿转载和采集!