Search code examples
javascriptsafari

How to make trimStart() function available on Safari? Create if not defined


I have noticed that string.trimStart() is not available on Safari 11 and before.

Using it yields the error:

trimStart is not a function

What the function does:

The trimStart() method removes whitespace from the beginning of a string. trimLeft() is an alias of this method.

Is there a way to "create" this trimStart() function for Safari if it is not available? So calling it does not give undefined anymore but instead uses the self-defined prototype?

Maybe this would work:

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

I wonder if this overrides the built-in trimStart() safely without conflict?


Solution

  • You can use simple regex for replacing white space from the beginning of the text.

    if (!String.prototype.trimStart) {
      String.prototype.trimStart = function() { 
        return this.replace(/^\s+/, ""); 
      }
    }
    
    let str = '    something.  ';
    const result = str.trimStart();
    
    console.log(result) // trim the starting whitepsace;
    console.log(result.length)  // get the length of the string with the white space at the end.
    console.log(result + 'else') // showing the whitespace at the end of str