摘要: 本文主要探讨了在 JavaScript 语言中如何有效地去除文本中的所有换行符。通过分析不同的方法和技术,提供了实用的解决方案,并对其性能和适用性进行了评估。
let text = "This is a line.\nThis is another line.";
let result = text.replace(/\r?\n|\r/g, "");
console.log(result);
let text = "This is a line.\nThis is another line.";
let result = text.split(/\r?\n|\r/).join("");
console.log(result);
let text = "This is a line.\nThis is another line.";
let startTime, endTime;
startTime = performance.now();
for (let i = 0; i < 100000; i++) {
text.replace(/\r?\n|\r/g, "");
}
endTime = performance.now();
console.log(`正则表达式方法耗时:${endTime - startTime} 毫秒`);
startTime = performance.now();
for (let i = 0; i < 100000; i++) {
text.split(/\r?\n|\r/).join("");
}
endTime = performance.now();
console.log(`split 和 join 方法耗时:${endTime - startTime} 毫秒`);