我如何从字符串的开始和结束删除所有空白?
当前回答
下面是它的TypeScript格式:
var trim: (input: string) => string = String.prototype.trim
? ((input: string) : string => {
return (input || "").trim();
})
: ((input: string) : string => {
return (input || "").replace(/^\s+|\s+$/g,"");
})
如果本机原型不可用,它将回退到正则表达式。
其他回答
如果使用jQuery,请使用jQuery.trim()函数。例如:
if( jQuery.trim(StringVariable) == '')
JavaScript修剪的通用函数是什么?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
使用简单的代码
var str = " Hello World! ";
alert(str.trim());
浏览器支持
Feature Chrome Firefox Internet Explorer Opera Safari Edge
Basic support (Yes) 3.5 9 10.5 5 ?
为旧浏览器添加原型
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
我有一个库,使用修剪。所以通过使用下面的代码来解决它。
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
不知道有什么虫子可以藏在这里,但我用这个:
var some_string_with_extra_spaces=" goes here "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
或者这个,如果文本包含回车:
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
另一个尝试:
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])