ez-common-ts/src/commons/str-utils.ts

76 lines
2.3 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.

/**
* 生成给定函数体的函数注释。
*
* @param {RegExp} regExp - 用于匹配的正则表达式。
* @param {(text: string, match: boolean) => T} matchHandler - 处理匹配到的文本的函数。
* @param {(text: string, match: boolean) => T} [textHandler] - 处理未匹配到的文本的函数。
* @return {(str: string) => T[]} - 分词器函数。
*/
export function stringTokenizer<T>(
regExp: RegExp,
matchHandler: (text: string, match: boolean) => T,
textHandler?: (text: string, match: boolean) => T
): (str: string) => T[] {
const ifMatch = matchHandler;
const ifText = textHandler?textHandler: matchHandler;
return function (str: string) {
const result: T[] = [];
const matches = str.matchAll(regExp);
let index = 0;
for (const match of matches) {
const before = str.slice(index, match.index);
if (before) {
result.push(ifText(before, false));
}
result.push(ifMatch(match[0], true));
index = match.index! + match[0].length;
}
if (index < str.length) {
result.push(ifText(str.slice(index), false));
}
return result;
};
}
/**
* 该函数接受两个参数,判断它们是否相等,不区分大小写。
* 如果参数都是字符串类型,则将它们转换为小写后比较。
* 如果两个参数都是undefined则返回true
* 否则返回false。
* @param source
* @param target
* @returns
*/
export function equalsIgnoreCase(
source: string | undefined,
target: string | undefined
) {
if (typeof source === "string" && typeof target === "string") {
return source.toLowerCase() === target.toLowerCase();
} else if (source === undefined && target === undefined) {
return true;
}
return false;
}
/**
* 这个函数接受一个字符串数组和一个字符串作为参数,
* 在数组中判断是否存在与搜索字符串相同或相似的字符串,忽略大小写。
* 如果找到匹配项则返回true否则返回false。
* @param list 字符串数组
* @param search 用来搜索的字符串
* @returns 是否包含
*/
export const includeIgnoreCase = (list: string[], search: string) => {
for (let i = 0; i < list.length; i++) {
let item = list[i];
if (equalsIgnoreCase(item, search)) {
return true;
}
}
return false;
};