如何用JavaScript不调用内置方法去除字符串首尾及多余空白字符
JavaScript实现无内置方法去除字符串首尾及内部多余空白
需求说明
不调用JavaScript字符串内置的trim、replace等处理方法,实现去除字符串首尾空白字符(空格、制表符\t、换行符\n),同时合并字符串内部的连续空白字符为单个空格。
原代码问题说明
参考C语言实现的逻辑存在两个核心适配问题:
- JavaScript中的字符串是不可变原始类型,无法通过
str[i] = xxx的方式直接修改字符串单个字符 - 原有C逻辑仅处理了首尾空白,没有实现内部多余空白的合并
实现代码
var str = " Lots of leading space! Hello World "; var result = ""; var isPrevSpace = false; var startIndex = 0; var endIndex = str.length - 1; // 定位第一个非空白字符位置,跳过前导空白 while (startIndex <= endIndex && (str[startIndex] === ' ' || str[startIndex] === '\t' || str[startIndex] === '\n')) { startIndex++; } // 定位最后一个非空白字符位置,跳过尾部空白 while (endIndex >= startIndex && (str[endIndex] === ' ' || str[endIndex] === '\t' || str[endIndex] === '\n')) { endIndex--; } // 遍历中间内容,合并内部连续空白为单个空格 for (var i = startIndex; i <= endIndex; i++) { var currentChar = str[i]; if (currentChar === ' ' || currentChar === '\t' || currentChar === '\n') { if (!isPrevSpace) { result += ' '; isPrevSpace = true; } } else { result += currentChar; isPrevSpace = false; } } console.log(result); // 输出:Lots of leading space! Hello World
逻辑说明
- 先通过两次循环定位字符串首尾第一个非空白字符的下标,直接过滤所有首尾空白
- 遍历首尾之间的所有字符,用标记位记录上一个字符是否为空白,仅当前后字符为非空白+空白组合时才往结果中拼接单个空格,非空白字符直接拼接即可
内容的提问来源于stack exchange,提问作者Alpha Momin
相关产品推荐
相关产品推荐

