Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading