JavaScript似乎没有本地的trim()
方法。使用JavaScript如何修剪字符串开头和结尾的空格?
JavaScript似乎没有本地的trim()
方法。使用JavaScript如何修剪字符串开头和结尾的空格?
// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
使用方法如下
var myString = " some text ";
alert(myString.trim());
例子
// Adding trim function to String object if its not there
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
var str = " some text ";
console.log(str.trim());
微软 .NET 也有 String.trim 函数作为 JavaScript 基础类型扩展的一部分。如果你正在编写 ASP.NET 应用程序,它可以被使用。
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
许多JavaScript问题的答案:jQuery
$j.trim(string)
注意:以上假设您的jQuery已经设置好:
<script type="text/javascript">$j = jQuery.noConflict();</script>
这比"$"更明智,比每次输入"jQuery"更简洁。
$("#start-date").text().trim()
我使用这个:
处理函数。
function trim($) {
return (typeof $ == "function" ? $() : $).replace(/[\s]*/g,"")
}
code example:
trim((function(){ return "a b"})) // ab
trim(" a b") //ab
您可以使用以下内容...
function trim(str) {
try {
if (str && typeof(str) == 'string') {
return str.replace(/^\s*|\s*$/g, "");
} else {
return '';
}
} catch (e) {
return str;
}
}
function Trim(obj) {
var coll = "";
var arrObj = obj.split(' ');
for (var i=0;i<arrObj.length;i++) {
if (arrObj[i] == "") {
arrObj.splice(i,1); // removes array indices containing spaces
}
}
//alert(arrObj.length); // should be equal to the number of words
// Rebuilds with spaces in-between words, but without spaces at the end
for (var i=0;i<arrObj.length;i++) {
if (arrObj[i] != "" && i != arrObj.length-1)
coll += arrObj[i] + " ";
if (arrObj[i] != "" && i == arrObj.length-1)
coll += arrObj[i];
}
return coll;
}
$j
比$
更合理? - Ben