Javascript - Apply trim function to each string in an array

后端 未结 11 1332
-上瘾入骨i
-上瘾入骨i 2020-12-07 14:22

Want to trim each string in an array, e.g., given

x = [\' aa \', \' bb \'];

output

[\'aa\', \'bb\']

My fi

相关标签:
11条回答
  • 2020-12-07 14:57

    Or this can be solved with arrow functions:

    x.map(s => s.trim());
    
    0 讨论(0)
  • 2020-12-07 14:57

    Another ES6 alternative

    const row_arr = ['a ', ' b' , ' c ', 'd'];
    const trimed_arr = row_arr.map(str => str.trim());
    console.log(trimed_arr); // <== ['a', 'b', 'c', 'd']
    
    0 讨论(0)
  • 2020-12-07 14:59

    If you are using JQuery, then a better way to do this, as it will work with IE8 as well (I need to support IE8) is this:

    $.map([' aa ', ' bb ', '   cc '], $.trim);
    
    0 讨论(0)
  • 2020-12-07 14:59

    The simple variant without dependencies:

     for (var i = 0; i < array.length; i++) {
         array[i] = array[i].trim()
     }
    

    ES6 variant:

    const newArray = oldArray.map(string => string.trim())
    

    ES6 function variant:

    const trimmedArray = array => array.map(string => string.trim())
    
    0 讨论(0)
  • 2020-12-07 15:02

    String.prototype.trim.apply is the Function.prototype.apply method without being bound to trim. map will invoke it with the string, the index and the array as arguments and nothing (undefined) for the thisArg - however, apply expects to be called on functions:

    var apply = String.prototype.trim.apply;
    apply.call(undefined, x[0], 0, x) // TypeError
    

    What you can do is passing the trim function as the context for call:

    [' aa ', ' bb '].map(Function.prototype.call, String.prototype.trim)
    // ['aa', 'bb']
    

    What happens here is

    var call = Function.prototype.call,
        trim = String.prototype.trim;
    call.call(trim, x[0], 0, x) ≡
          trim.call(x[0], 0, x) ≡
                x[0].trim(0, x); // the arguments don't matter to trim
    
    0 讨论(0)
提交回复
热议问题