我如何从字符串的开始和结束删除所有空白?
当前回答
从angular js项目中修剪代码
var trim = (function() {
// if a reference is a `String`.
function isString(value){
return typeof value == 'string';
}
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return isString(value) ?
value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
};
}
return function(value) {
return isString(value) ? value.trim() : value;
};
})();
并将其命名为trim(" hello ")
其他回答
我知道这个问题三年前就有人问过了。现在,String.trim()是在JavaScript中原生添加的。举个例子,你可以像下面这样直接修剪,
document.getElementById("id").value.trim();
使用简单的代码
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 = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"
你可以使用纯JavaScript来实现:
function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
// Let's test it
sentenceOne = "too short";
sentencetwo = "more than the max length";
console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));
不知道有什么虫子可以藏在这里,但我用这个:
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])
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何删除表中特定列的第一个字符?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?