Python去除指定非空白字符的strip方法的TypeScript等效实现
实现TypeScript版的Python-style
strip()方法 TypeScript原生的trim()只能去除字符串首尾的空白字符,没法像Python的strip()那样指定要移除的非空白字符。这里有两种实用的实现方式:
方法一:正则表达式实现(简洁高效)
利用正则匹配首尾的指定字符并替换为空,注意要先转义正则的特殊字符(比如.、*这类),避免匹配出错:
function strip(str: string, chars: string): string { // 转义正则元字符,避免匹配逻辑混乱 const escapedChars = chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 构建正则:匹配开头或结尾的指定字符序列 const trimRegex = new RegExp(`^[${escapedChars}]+|[${escapedChars}]+$`, 'g'); return str.replace(trimRegex, ''); }
测试示例:
const s = "/abc/def/pop/"; console.log(strip(s, '/')); // 输出: "abc/def/pop" const s2 = "###hello world###"; console.log(strip(s2, '#')); // 输出: "hello world" // 处理包含正则特殊字符的场景 const s3 = "....test..."; console.log(strip(s3, '.')); // 输出: "test"
方法二:手动遍历实现(无正则依赖)
如果不想用正则,也可以通过遍历字符串首尾,定位到需要保留的区间:
function strip(str: string, chars: string): string { let startIdx = 0; // 从左往右找第一个不在指定字符集合里的位置 while (startIdx < str.length && chars.includes(str[startIdx])) { startIdx++; } let endIdx = str.length - 1; // 从右往左找第一个不在指定字符集合里的位置 while (endIdx >= startIdx && chars.includes(str[endIdx])) { endIdx--; } // 截取保留区间的子串 return str.slice(startIdx, endIdx + 1); }
测试示例:
const s = "/abc/def/pop/"; console.log(strip(s, '/')); // 输出: "abc/def/pop" const s4 = "xxxyyyzzz"; console.log(strip(s4, 'xyz')); // 输出: ""(所有字符都在指定集合中)
扩展:支持默认去除空白
如果想和Python的strip()完全对齐,不传chars参数时默认去除空白字符,可以给参数加默认值:
function strip(str: string, chars: string = ' \t\n\r\v\f'): string { const escapedChars = chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const trimRegex = new RegExp(`^[${escapedChars}]+|[${escapedChars}]+$`, 'g'); return str.replace(trimRegex, ''); } // 测试默认空白去除 const s5 = " hello world \n"; console.log(strip(s5)); // 输出: "hello world"
内容的提问来源于stack exchange,提问作者OrenIshShalom
相关产品推荐
相关产品推荐

