我如何从字符串的开始和结束删除所有空白?
当前回答
不知道有什么虫子可以藏在这里,但我用这个:
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])
其他回答
如果你已经在使用jQuery框架,那么从jQuery修剪是很方便的。
$.trim(' your string ');
我倾向于经常使用jQuery,所以用它修剪字符串对我来说是很自然的。但是否有可能出现反对jQuery的声音?:)
如果使用jQuery,请使用jQuery.trim()函数。例如:
if( jQuery.trim(StringVariable) == '')
我的使用一个regex来寻找需要修剪的情况,并使用regex的结果来确定所需的子字符串边界:
var illmatch= /^(\s*)(?:.*?)(\s*)$/
function strip(me){
var match= illmatch.exec(me)
if(match && (match[1].length || match[2].length)){
me= me.substring(match[1].length, p.length-match[2].length)
}
return me
}
其中的一个设计决策是使用子字符串执行最终捕获。/ \ ?://(捕获中间项)并且替换片段变成:
if(match && (match[1].length || match[3].length)){
me= match[2]
}
我在这些建议中做了两个性能赌注:
子字符串实现复制原始字符串的数据吗?如果是这样,在第一种情况下,当一个字符串需要修整时,会有两次遍历,第一次在正则表达式中(希望是部分的),第二次在子字符串提取中。希望子字符串实现只引用原始字符串,这样像substring这样的操作几乎是免费的。交叉手指 正则表达式impl中的捕获有多好?中间项,也就是输出值,可能会很长。我还没有准备好银行所有的regex impls的捕获不会阻止几百KB的输入捕获,但我也没有测试(太多的运行时,对不起!)第二个ALWAYS运行捕获;如果你的引擎可以做到这一点而不受影响,也许可以使用上面的一些技巧,那就一定要使用它!
使用简单的代码
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, '');
};
}
你可以使用纯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));