🚀 写一个去除制表符和换行符的方法
欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。
一、核心方法:去除制表符和换行符
const removeTabsAndNewlines = str =>
str.replace(/[\t\n]/g, '');
const exampleString = "Hello,\tWorld!\nThis is a test.";
const result = removeTabsAndNewlines(exampleString);
console.log(result);
⚠️ 重要提示
[\t\n] 不能改成 \t\n
/[\t\n]/g 匹配制表符 或 换行符 /\t\n/g 匹配制表符 后紧跟 换行符的连续字符
二、扩展方法:去除所有空白字符
方法 1:使用 \s(推荐)
const removeAllWhitespace = str =>
str.replace(/\s/g, '');
const example = "Hello,\t World!\n This is a test.";
console.log(removeAllWhitespace(example));
方法 2:明确指定字符类
const removeSpecificWhitespace = str =>
str.replace(/[ \t\n\r]/g, '');
const example = "Hello,\t World!\n This is a test.";
console.log(removeSpecificWhitespace(example));
三、对比:去除非单词字符
方法:去除标点符号和空格
const removePunctuationAndSpaces = str =>
str.replace(/[^\w]/g, '');
const removePunctuationAndSpaces2 = str =>
str.replace(/\W/g, '');
const example = "Hello, World! This is a test.";
console.log(removePunctuationAndSpaces(example));
四、方法对比总结
| 方法 | 正则表达式 | 移除内容 | 适用场景 |
| 去除制表符和换行符 | /[\t\n]/g | 制表符、换行符 | 保留空格,只移除特定空白字符 |
| 去除所有空白字符 | /\s/g | 空格、制表符、换行符、回车符等 | 移除所有空白,紧凑显示 |
| 去除非单词字符 | /\W/g 或 /[^\w]/g | 标点符号、空格、特殊字符 | 只保留字母、数字、下划线 |
| 去除指定字符 | /[ \t\n\r]/g | 明确指定的字符 | 精确控制移除内容 |
五、常见错误示例
❌ 错误写法 1:使用 \t\n
const wrong1 = str => str.replace(/\t\n/g, '');
const test = "A\tB\nC\t\nD";
console.log(wrong1(test));
❌ 错误写法 2:忘记全局标志 g
const wrong2 = str => str.replace(/[\t\n]/, '');
const test = "A\tB\nC";
console.log(wrong2(test));
六、实战应用场景
✅ 场景 1:处理用户输入
const cleanUserInput = input => {
return input
.replace(/[\t\n\r]/g, '')
.replace(/\s+/g, ' ')
.trim();
};
const input = " Hello,\t\n World! \n";
console.log(cleanUserInput(input));
✅ 场景 2:处理 CSV 数据
const cleanCSVField = field => {
return field.replace(/[\n\r]/g, ' ').trim();
};
const csvField = "Product\nName";
console.log(cleanCSVField(csvField));
✅ 场景 3:生成 URL 友好字符串
const generateSlug = text => {
return text
.toLowerCase()
.replace(/[\t\n\r]/g, '')
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-');
};
const title = "Hello,\tWorld!\nThis is a Test";
console.log(generateSlug(title));
七、完整测试代码
const removeTabsAndNewlines = str => str.replace(/[\t\n]/g, '');
const test1 = "Hello,\tWorld!\nThis is a test.";
console.log(removeTabsAndNewlines(test1));
const removeAllWhitespace = str => str.replace(/\s/g, '');
const test2 = "Hello,\t World!\n This is a test.";
console.log(removeAllWhitespace(test2));
const removePunctuation = str => str.replace(/\W/g, '');
const test3 = "Hello, World! This is a test.";
console.log(removePunctuation(test3));
const cleanInput = input => {
return input
.replace(/[\t\n\r]/g, '')
.replace(/\s+/g, ' ')
.trim();
};
const test4 = " Hello,\t\n World! \n";
console.log(cleanInput(test4));
八、核心要点总结
💡 记住这些要点
- [\t\n] = 匹配制表符 或 换行符(字符类)
- \t\n = 匹配制表符 后紧跟 换行符(连续匹配)
- \s = 匹配所有空白字符(空格、制表符、换行符等)
- \W = 匹配非单词字符(等价于 [^\w])
- 使用 g 标志 进行全局替换