使用javascript在两端修剪字符串

Red*_*ddy 2 javascript string trim

可能重复:
如何在javascript中修剪字符串?

我有下面的字符串来自ajax响应

"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\tERROR: Profile : NOT SUCCESS\nCODE        : 2\nCATEGORY    : TECHNICAL\nSEVERITY    : null\nENVIRONMENT : DEV\nAPPLICATION : DEV\nDESCRIPTION : Profile: INVOCATION UNHANDLED EXCEPTION [null]\nDESCRIPTION : Profile: [ServiceAttribute]\nDESCRIPTION : Profile: Instance ID = 20130108124231841\n\r\n\r\n"
Run Code Online (Sandbox Code Playgroud)

我使用下面的代码修剪两端的字符串.

var text = originalRequest.responseText.replace(/ ^\s + |\s + $/g,'');

然而,它正在删除来自ajax响应的消息之间的\n.我最终想要的是

"ERROR: Profile : NOT SUCCESS
CODE        : 2
CATEGORY    : TECHNICAL
SEVERITY    : null
ENVIRONMENT : DEV
APPLICATION : DEV
DESCRIPTION : Profile: INVOCATION UNHANDLED EXCEPTION [null]
DESCRIPTION : Profile: [ServiceAttribute]
DESCRIPTION : Profile: Instance ID = 20130108124231841"
Run Code Online (Sandbox Code Playgroud)

我怎么得到这个?尝试从过去1小时不同的方式:(

Cer*_*rus 5

只需使用trim();:

var s = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\tERROR: Profile : NOT SUCCESS\nCODE        : 2\nCATEGORY    : TECHNICAL\nSEVERITY    : null\nENVIRONMENT : DEV\nAPPLICATION : DEV\nDESCRIPTION : Profile: INVOCATION UNHANDLED EXCEPTION [null]\nDESCRIPTION : Profile: [ServiceAttribute]\nDESCRIPTION : Profile: Instance ID = 20130108124231841\n\r\n\r\n";
console.log(s.trim());

"ERROR: Profile : NOT SUCCESS
CODE        : 2
CATEGORY    : TECHNICAL
SEVERITY    : null
ENVIRONMENT : DEV
APPLICATION : DEV
DESCRIPTION : Profile: INVOCATION UNHANDLED EXCEPTION [null]
DESCRIPTION : Profile: [ServiceAttribute]
DESCRIPTION : Profile: Instance ID = 20130108124231841"
Run Code Online (Sandbox Code Playgroud)

如果trim()不可用(IE 8-),请尝试以下填充:

if(!String.prototype.trim) {
    String.prototype.trim = function () { 
        return this.replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g,'');
    });
}
Run Code Online (Sandbox Code Playgroud)