JavaScript Snippet – String.prototype.before()

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.

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. :cool:

3 thoughts on “JavaScript Snippet – String.prototype.before()”

  1. 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 = {} == ‘[object RegExp]’,” instead of “isRegExp = target instanceof RegExp” ?

    1. * 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.

Leave a Reply

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

three + = 7

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">