WARNING:
Extending native prototypes is frowned upon by many JS engineers but can be helpful as long as the extensions are properly documented in the codebase.
SCRIPTER’S DISCRETION IS ADVISED. 😆

Even though its NOT encouraged to extend native prototypes, at times you may find that doing so is pretty useful. One extension that you may find useful is String.prototype.before(...) which can be used to return the substring before a specified target. Here is the definition:

First I think its worth mentioning that depending on your preference you could choose to rename this function as String.prototype.leftOf(...) to clearly identify what it does. This function takes at least a target to find in the string which is either a string or a regexp. You may also optionally pass in a second argument which indicates the occurrence of the target to key off of. For example, if you wanted to extract the substring before the second comma in "one, two, three, and four" you could do something like the following:


var str = "one, two, three, and four";
var firstTwo = str.before(',', 2);

Of course, that is just one simple example of what you can do with this prototype extension. Check out some tests that exemplify how to use this helpful function:

Most likely if you like this function you will also want to check out the String.prototype.after(...) post. Enjoy using this helpful utility function. 😎


3 Comments

Arnaud Buchholz · January 21, 2015 at 11:23 AM

Thank you for sharing this.

If you don’t mind, I have two remarks:
– Can you explain why it is “NOT encouraged to extend native prototypes” ?

– Why did you use isRegExp = {}.toString.call(target) == ‘[object RegExp]’,” instead of “isRegExp = target instanceof RegExp” ?

    Chris West · January 21, 2015 at 3:22 PM

    * One of the main issues with prototypal extension is that a lot of third-party code (libraries included) do it and a developer may expect one result, but something else may happen because of the differences in the definitions. At times too, one library’s implementation of a prototypal extension may accept a different amount of arguments than another does.
    * I am using toString so that if this function is passed a RegExp from another frame it will still be recognized as a RegExp and not just as random object.

JavaScript Snippet – String.prototype.after() | Chris West's Blog · January 21, 2015 at 2:49 PM

[…] I added a post about String.prototype.before(…). As is explained within the post, this function can be used to easily extract a substring before a […]

Leave a Reply to JavaScript Snippet – String.prototype.after() | Chris West's Blog Cancel reply

Your email address will not be published. Required fields are marked *