需要去除字符串首尾的空白字符(換行、空格、Tab 等),但保留中間的換行。類似 `trim()` 行為,但老環境無原生支持。
const str = '\n Hello World \r\n';
const trimmed = str.trim(); // "Hello World"
`String.prototype.trim()` 已標準化,可直接使用。
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
function trimNewlines(str) {
return str.replace(/^[\r\n]+|[\r\n]+$/g, '');
}
若只針對 `\r` `\n`,用字符類 `[\r\n]` 更精確。
const test = '\n\r Hello\nWorld \r\n';
console.log('|' + test.trim() + '|'); // |Hello\nWorld|
console.log('|' + trimNewlines(test) + '|'); // | Hello\nWorld |