Cocos Creator 3.8.1中TypeScript字符串替换方法异常求助
问题:Cocos Creator v3.8.1中TypeScript的replace方法无法实现预期的空格添加效果
需求:将字符串的字母之间添加单个空格,单词之间添加3个空格。
原代码:
let testStr : string = "test string"; testStr = testStr.toUpperCase().replace(' ','#').split('').join(' ').replace('#',' '); console.log(testStr);
实际输出:
T E S T S T R I N G
问题原因
原代码逻辑存在漏洞:
replace(' ', '#')仅替换第一个空格(非全局替换),若字符串有多个空格会直接失效;split('').join(' ')会把临时标记#也拆分为单独字符,导致#前后被自动添加空格,后续replace('#',' ')执行后,单词间仅能得到2个空格,且逻辑完全依赖临时标记,容错性差。
解决方法
方法一:拆分单词后分别处理(直观可靠)
先按空格拆分单词,给每个单词的字母间添加空格,最后用3个空格拼接所有单词:
let testStr: string = "test string"; // 转大写后拆分单词 const words = testStr.toUpperCase().split(' '); // 给每个单词的字母间添加单个空格 const processedWords = words.map(word => word.split('').join(' ')); // 用3个空格拼接处理后的单词 testStr = processedWords.join(' '); console.log(testStr);
输出结果:
T E S T S T R I N G
方法二:正则表达式全局替换
通过正则精准匹配字母和单词间隔,一次性完成替换:
let testStr: string = "test string"; testStr = testStr.toUpperCase() // 给每个字母后添加单个空格 .replace(/([A-Z])/g, '$1 ') // 将单词间的连续空格替换为3个空格,同时保留字母间的单个空格 .replace(/(\s+)(?=[A-Z])/g, (match) => match.length > 1 ? ' ' : ' ') // 移除字符串末尾多余的空格 .trim(); console.log(testStr);
内容的提问来源于stack exchange,提问作者user21109846
相关产品推荐
相关产品推荐

