如何修剪JavaScript中的字符串?
答案 0 :(得分:873)
IE9 +以来的所有浏览器都有trim()
。
对于那些不支持trim()
的浏览器,您可以使用MDN中的此polyfill:
if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
见:
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
答案 1 :(得分:479)
如果您已经在使用该框架,则jQuery的修剪很方便。
$.trim(' your string ');
我倾向于经常使用jQuery,因此使用它修剪字符串对我来说很自然。但是有可能在那里对jQuery产生强烈反对? :)
答案 2 :(得分:163)
虽然上面有一堆正确答案,但应注意JavaScript中的String
对象具有 ECMAScript 5 的原生.trim()
方法。因此,理想情况下,任何对trim方法进行原型设计的尝试都应该先检查它是否已经存在。
if(!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
原生添加: JavaScript 1.8.1 / ECMAScript 5
因此支持:
Firefox: 3.5 +
Safari: 5 +
Internet Explorer: IE9 + (仅限于标准模式!)http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx
Chrome: 5 +
Opera: 10.5 +
ECMAScript 5支持表:http://kangax.github.com/es5-compat-table/
答案 3 :(得分:126)
可以使用a lot of implementations。最明显的似乎是这样的:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"
答案 4 :(得分:46)
简单版本What is a general function for JavaScript trim?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
答案 5 :(得分:28)
我知道这个问题已在三年前被问过了。现在,String.trim()
是在JavaScript中本地添加的。例如,你可以直接修剪如下,
document.getElementById("id").value.trim();
答案 6 :(得分:21)
如果您使用的是jQuery,请使用jQuery.trim()
功能。例如:
if( jQuery.trim(StringVariable) == '')
答案 7 :(得分:20)
Flagrant Badassery 有11种不同的修剪基准信息:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
令人惊讶的是,基于正则表达式比传统循环慢。
这是我个人的。这段代码很旧!我为JavaScript1.1和Netscape 3编写了它,之后它只是略有更新。 (原文使用String.charAt)
/**
* Trim string. Actually trims all control characters.
* Ignores fancy Unicode spaces. Forces to string.
*/
function trim(str) {
str = str.toString();
var begin = 0;
var end = str.length - 1;
while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
while (end > begin && str.charCodeAt(end) < 33) { --end; }
return str.substr(begin, end - begin + 1);
}
答案 8 :(得分:13)
使用原生JavaScript方法:String.trimLeft()
,String.trimRight()
和String.trim()
。
IE9+ and all other major browsers支持String.trim()
:
' Hello '.trim() //-> 'Hello'
String.trimLeft()
和String.trimRight()
是非标准的,但all major browsers except IE
' Hello '.trimLeft() //-> 'Hello '
' Hello '.trimRight() //-> ' Hello'
然而,使用polyfill可以轻松支持IE:
if (!''.trimLeft) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,'');
};
String.prototype.trimRight = function() {
return this.replace(/\s+$/,'');
};
if (!''.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
}
答案 9 :(得分:11)
答案 10 :(得分:10)
String.prototype.trim = String.prototype.trim || function () {
return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.trimLeft = String.prototype.trimLeft || function () {
return this.replace(/^\s+/, "");
};
String.prototype.trimRight = String.prototype.trimRight || function () {
return this.replace(/\s+$/, "");
};
String.prototype.trimFull = String.prototype.trimFull || function () {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};
从Matt duereg无耻地偷走。
答案 11 :(得分:7)
修剪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 ")
答案 12 :(得分:4)
简单地使用代码
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, '');
};
}
答案 13 :(得分:4)
这是一个非常简单的方法:
function removeSpaces(string){
return string.split(' ').join('');
}
答案 14 :(得分:3)
您可以将变量声明为字符串并使用其trim函数:
var str = new String('my string');
str= str.trim();
答案 15 :(得分:2)
今天,几乎每个浏览器都支持String.prototype.trim()
。
你这样使用它:
var origStr = ' foo ';
var newStr = origStr.trim(); // Value of newStr becomes 'foo'
如果您仍然可能需要支持不支持此功能的古老浏览器,则MDN会建议a polyfill:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
答案 16 :(得分:1)
我有一个使用trim的lib。所以通过使用以下代码解决了它。
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
答案 17 :(得分:1)
if(!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/gm,'');
};
}
根据之前的答案,它与添加标志m
不同。
标记m
将搜索多个线性文本。在此模式下,标记模式的开头和结尾(^
$
)将在换行符(\n
)之前和之后插入。
答案 18 :(得分:0)
在本地的 String 上使用async
是最简单的方法:
trim()
答案 19 :(得分:0)
这里是TypeScript:
var trim: (input: string) => string = String.prototype.trim
? ((input: string) : string => {
return (input || "").trim();
})
: ((input: string) : string => {
return (input || "").replace(/^\s+|\s+$/g,"");
})
如果本机原型不可用,它将回退到正则表达式。
答案 20 :(得分:0)
我在2008年以JS方式提供.trim()函数时,我已经为trim编写了这个函数。一些旧的浏览器仍然不支持.trim()函数,我希望这个函数可以帮助某人。
TRIM FUNCTION
function trim(str)
{
var startpatt = /^\s/;
var endpatt = /\s$/;
while(str.search(startpatt) == 0)
str = str.substring(1, str.length);
while(str.search(endpatt) == str.length-1)
str = str.substring(0, str.length-1);
return str;
}
解释:函数trim()接受一个字符串对象并删除任何起始和尾随空格(空格,制表符和换行符)并返回剪裁后的字符串。您可以使用此功能修剪表单输入以确保发送有效数据。
可以通过以下方式调用该函数作为示例。
form.elements[i].value = trim(form.elements[i].value);
答案 21 :(得分:0)
不知道这里可以隐藏什么错误,但我用这个:
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])
答案 22 :(得分:0)
您可以使用纯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));
答案 23 :(得分:-1)
现在trim()内置在javascript中。
let yourName = ' something ';
let actualTrimmedName = yourName.trim();
仅通过控制台或打印代码,您的姓名也会被剪裁。
答案 24 :(得分:-4)
我使用单个正则表达式来查找需要修剪的情况,并使用该正则表达式的结果来确定所需的子字符串边界:
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
}
进入此项的一个设计决策是使用子字符串来执行最终捕获。 s / \?://(使中间项捕获)并且替换片段变为:
if(match && (match[1].length || match[3].length)){
me= match[2]
}
我在这些推动中做了两个表现性的赌注:
子串实现是否复制了原始字符串的数据?如果是这样,在第一个中,当需要修剪一个字符串时,会有一个双遍历,首先在正则表达式中(可能希望是部分),然后是子字符串提取中的第二个遍历。希望子字符串实现只引用原始字符串,因此像substring这样的操作几乎是免费的。 交叉手指
正则表达式中的捕获有多好?中期,产值可能会很长。我还没有准备好保证所有正则表达式的推测'捕获不会对几百KB的输入捕获不感兴趣,但我也没有测试(运行时太多,抱歉!)。第二个ALWAYS运行捕获;如果您的引擎可以在不受击中的情况下执行此操作,可能使用上述一些字符串绳索技术,确保使用它!
答案 25 :(得分:-7)
对于IE9 +和其他浏览器
function trim(text) {
return (text == null) ? '' : ''.trim.call(text);
}