简体   繁体   English

在 JavaScript 中修剪字符串

[英]Trim string in JavaScript

如何从字符串的开头和结尾删除所有空格?

The trim from jQuery is convenient if you are already using that framework.如果您已经在使用该框架,那么来自jQuery的修剪会很方便。

$.trim('  your string   ');

I tend to use jQuery often, so trimming strings with it is natural for me.我倾向于经常使用 jQuery,所以用它修剪字符串对我来说很自然。 But it's possible that there is backlash against jQuery out there?但是有可能对 jQuery 有强烈反对吗? :) :)

Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5 .虽然上面有一堆正确的答案,但应该注意的是,JavaScript 中的String对象在ECMAScript 5中有一个原生的.trim()方法。 Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.因此,理想情况下,任何对 trim 方法进行原型设计的尝试都应该首先检查它是否已经存在。

if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
}

Added natively in: JavaScript 1.8.1 / ECMAScript 5原生添加于: JavaScript 1.8.1 / ECMAScript 5

Thus supported in:因此支持:

Firefox: 3.5+火狐: 3.5+

Safari: 5+野生动物园: 5+

Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx 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+铬: 5+

Opera: 10.5+歌剧: 10.5+

ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/ ECMAScript 5 支持表:http: //kangax.github.com/es5-compat-table/

There are a lot of implementations that can be used.很多实现可以使用。 The most obvious seems to be something like this:最明显的似乎是这样的:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

" foo bar ".trim();  // "foo bar"

Simple version here What is a general function for JavaScript trim?简单版在这里JavaScript trim 的通用功能是什么?

function trim(str) {
        return str.replace(/^\s+|\s+$/g,"");
}

我知道三年前就有人问过这个问题。现在, String.trim()是在 JavaScript 中原生添加的。例如,您可以直接修剪如下,

document.getElementById("id").value.trim();

If you are using jQuery, use the jQuery.trim() function.如果您使用 jQuery,请使用jQuery.trim()函数。 For example:例如:

if( jQuery.trim(StringVariable) == '')

Flagrant Badassery has 11 different trims with benchmark information: Flagrant Badassery有 11 种带有基准信息的不同装饰:

http://blog.stevenlevithan.com/archives/faster-trim-javascript http://blog.stevenlevithan.com/archives/faster-trim-javascript

Non-surprisingly regexp-based are slower than traditional loop.毫不奇怪,基于正则表达式的速度比传统循环慢。


Here is my personal one.这是我个人的。 This code is old!这段代码很旧! I wrote it for JavaScript1.1 and Netscape 3 and it has been only slightly updated since.我为 JavaScript1.1 和 Netscape 3 编写了它,从那以后它只做了轻微的更新。 (Original used String.charAt) (原来用的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);
}

Use the Native JavaScript Methods: String.trimLeft() , String.trimRight() , and String.trim() .使用原生 JavaScript 方法: String.trimLeft()String.trimRight()String.trim()


String.trim() is supported in IE9+ and all other major browsers : IE9+ 和所有其他主流浏览器都支持String.trim()

'  Hello  '.trim()  //-> 'Hello'


String.trimLeft() and String.trimRight() are non-standard, but are supported in all major browsers except IE String.trimLeft()String.trimRight()是非标准的,但在除 IE 之外的所有主要浏览器中都支持

'  Hello  '.trimLeft()   //-> 'Hello  '
'  Hello  '.trimRight()  //-> '  Hello'


IE support is easy with a polyfill however: IE 支持很容易使用 polyfill,但是:

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, '');
        };
    }
}
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, " ");
};

Shamelessly stolen from Matt duereg .无耻地从马特杜雷格那里偷走

Now days you can use string.trim() that is native Javascript implementation 现在,您可以使用本机Javascript实现的string.trim()

var orig = "   foo  ";
console.log(orig.trim());//foo

See also 也可以看看

Trim code from angular js projectAngular 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;
  };

})();

and call it as trim(" hello ")并将其称为trim(" hello ")

["

use simply code<\/i>使用简单的代码<\/b><\/p>

var str = "       Hello World!        ";
alert(str.trim());

You can just declare your variable as string and use its trim function: 您可以将变量声明为字符串并使用其trim函数:

var str = new String('my string'); 
str= str.trim();

Here's a very simple way:这是一个非常简单的方法:

function removeSpaces(string){
return string.split(' ').join('');
}

Today, pretty much every browser supports String.prototype.trim() . 今天,几乎所有浏览器都支持String.prototype.trim()

You use it like this : 您可以这样使用它:

var origStr = '   foo  ';
var newStr = origStr.trim(); // Value of newStr becomes 'foo'

In case you still might need to support an ancient browser that doesn't support this feature, this is a polyfill suggested by the MDN : 如果您仍然需要支持不支持此功能的旧版浏览器,则这是MDN建议的polyfill:

if (!String.prototype.trim) {
    String.prototype.trim = function () {
       return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    };
}

Using trim() on String which is a native could be the easiest way: 在本地的String上使用trim()是最简单的方法:

 const fullName = " Alireza Dezfoolian "; const trimmedFullName = fullName.trim(); console.log(trimmedFullName); 

I have a lib that uses trim.我有一个使用修剪的库。 so solved it by using the following code.所以通过使用以下代码解决了它。

String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };

I had written this function for trim, when the .trim() function was not available in JS way back in 2008. Some of the older browsers still do not support the .trim() function and i hope this function may help somebody.早在 2008 年,当 .trim() 函数在 JS 中不可用时,我已经为 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;
}

Explanation : The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string.解释:函数 trim() 接受一个字符串对象并删除所有起始和尾随空格(空格、制表符和换行符)并返回修剪后的字符串。 You can use this function to trim form inputs to ensure valid data to be sent.您可以使用此功能修剪表单输入以确保发送有效数据。

The function can be called in the following manner as an example.以如下方式调用该函数为例。

form.elements[i].value = trim(form.elements[i].value);

You can do it using the plain JavaScript:你可以使用普通的 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));
if(!String.prototype.trim){  
  String.prototype.trim = function(){  
    return this.replace(/^\s+|\s+$/gm,'');  
  };  
}

From the previous answers, it differs adding flag m . 与先前的答案不同,添加标志m有所不同。

Flag m will search the text of several linear. 标志m将搜索几个线性文本。 In this mode, the mark the beginning and end of the pattern ( ^ $ ) is inserted before and after the newline character ( \\n ). 在这种模式下,模式的开始和结束标记( ^ $ )插入在换行符( \\n )之前和之后。

Don't know what bugs can hide here, but I use this:不知道这里可以隐藏什么错误,但我使用这个:

var some_string_with_extra_spaces="   goes here    "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])

Or this, if text contain enters:或者这个,如果文本包含输入:

console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])

Another try:另一个尝试:

console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])

Here it is in TypeScript:这是在 TypeScript 中:

var trim: (input: string) => string = String.prototype.trim
    ? ((input: string) : string => {
        return (input || "").trim();
    })
    : ((input: string) : string => {
        return (input || "").replace(/^\s+|\s+$/g,"");
    })

It will fall back to the regex if the native prototype is not available.如果原生原型不可用,它将回退到正则表达式。

Now trim() build in javascript. 现在trim()内置在javascript中。

let yourName = ' something   ';
let actualTrimmedName = yourName.trim();

just console or print code then your name will be trimmed as well. 只是控制台或打印代码,那么您的名字也会被修剪。

mine uses a single regex to look for cases where trimming is necessary, and uses that regex's results to determine desired substring bounds:我的使用单个正则表达式来查找需要修剪的情况,并使用该正则表达式的结果来确定所需的子字符串边界:

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
}

the one design decision that went into this was using a substring to perform the final capture.对此进行的一个设计决策是使用子字符串来执行最终捕获。 s/\?:// (make the middle term capturing) and and the replacement fragment becomes: s/\?:// (进行中间项捕获)并且替换片段变为:

    if(match && (match[1].length || match[3].length)){
        me= match[2]
    }

there's two performance bets I made in these impls:我在这些 impls 中做了两个性能赌注:

  1. does the substring implementation copy the original string's data?子字符串实现是否复制原始字符串的数据? if so, in the first, when a string needs to be trimmed there is a double traversal, first in the regex (which may, hopefully be partial), and second in the substring extraction.如果是这样,首先,当需要修剪字符串时,会进行双重遍历,首先是正则表达式(可能是部分),其次是子字符串提取。 hopefully a substring implementation only references the original string, so operations like substring can be nearly free.希望子字符串实现仅引用原始字符串,因此子字符串之类的操作几乎可以免费使用。 cross fingers十指交叉

  2. how good is the capture in the regex impl?正则表达式 impl 中的捕获有多好? the middle term, the output value, could potentially be very long.中期,即产出价值,可能会很长。 i wasn't ready to bank that all regex impls' capturing wouldn't balk at a couple hundred KB input capture, but i also did not test (too many runtimes, sorry!).我还没有准备好相信所有正则表达式 impls 的捕获不会在几百 KB 的输入捕获时犹豫,但我也没有测试(运行时太多,抱歉!)。 the second ALWAYS runs a capture;第二个总是运行捕获; if your engine can do this without taking a hit, perhaps using some of the above string-roping-techniques, for sure USE IT!如果您的引擎可以做到这一点而不会受到影响,也许使用上面的一些绳索技术,请务必使用它!

For IE9+ and other browsers适用于 IE9+ 等浏览器

function trim(text) {
    return (text == null) ? '' : ''.trim.call(text);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM