/** * 字符串工具类 * @author 袁浩 * */ export class StringUtils { public constructor() { } /** * 类似C#中的格式化字符串函数 * 例:format("Hello {0}",world) * @param str {string} 要格式化的字符串 * @param args {Array} 参数列表 * @returns {string} 格式化之后的字符串 */ public static format(str: string, ...args: Array): string { var result: string = str; for (var i: number = 0; i < args.length; i++) { var key = `{${i}}`; var value = String(args[i]); while (result.indexOf(key) != -1) { result = result.replace(key, value); } } return result; } /** * 判断是否是空字符串,null、undefined和""都会返回true * @returns {boolean} 是否是空字符串 */ public static isEmpty(value: string): boolean { return value == null || value == undefined || value.length == 0; } /** * 去左右两端空格 */ public static trim(str): string { return str.replace(/(^\s*)|(\s*$)/g, ""); } public static formatStar(str: string, beginLength = 2, endLength = 2) { var temp = str.split(""); var starLength = str.length - beginLength - endLength; var star = ''; for (let i = 0; i < starLength; i++) { star += '*'; } temp.splice(beginLength, starLength, star); return temp.join(""); } /** * 颜色配置 */ public static colorOption: { [key: string]: string } = { /** 红色1 */ red1: '#be2c1d', /** 棕色1 */ bro1: '#4E301B', /** 白色 */ white: '#FFFFFF', /** 白色 */ green: '#4AFF32', } public static getRichText(str: string, opt?: any) { opt = opt || this.colorOption; var newStr: string = str; var i: number = 0; var begin: number; var end: number; var sub: string; var searchValue: string; var replaceValue: string; var color_key: string; // 解析颜色 while (i < str.length) { begin = str.indexOf("[", i); end = str.indexOf("]", begin); if (begin != -1 && end != -1) {//把[redXXX]转成富文本 searchValue = str.slice(begin, end + 1); // 颜色内容 color_key = str.slice(begin + 1, begin + str.indexOf("=")); let color_str = opt[color_key] if (color_str) { sub = str.slice(begin + color_key.length + 2, end); replaceValue = '' + sub + ''; newStr = newStr.replace(searchValue, replaceValue); } i = end; } else { break; } } let size_index: number = 0; let size_begin: number = 0; let size_end: number = 0; let size_searchValue: string; // let size_sub: string // 解析尺寸{40=100%},100%是40尺寸.例子2:[bro对目标造成][red{40=104%}][bro攻击伤害] while (size_index < newStr.length) { size_begin = newStr.indexOf("{", size_index); size_end = newStr.indexOf("}", size_begin); if (size_begin != -1 && size_end != -1) { // 尺寸内容 size_searchValue = newStr.slice(size_begin, size_end + 1); let size_value = newStr.slice(size_begin + 1, size_begin + 3); let size_sub = size_searchValue.slice(4, size_searchValue.length - 1); if (size_sub) { let new_value = '' + size_sub + ''; newStr = newStr.replace(size_searchValue, new_value); } size_index = size_end; } else { break; } } return newStr; } }