Last active
August 29, 2015 14:08
-
-
Save jiggzson/443d14c7ca443c5b6aaa to your computer and use it in GitHub Desktop.
Gets between two provided brackets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This method gets between a bracket and returns what's between the brackets only | |
* after it's been balanced. This can be done with a regex however is microsecond | |
* optimizations aren't too important then this becomes a more versatile solution which | |
* can accept a multitude of brackets and braces. | |
* @param {String} ob The opening bracket or brace | |
* @param {String} cb The closing bracket or brace | |
* @param {String} str The string containing the brackets | |
* @param {Integer} start The starting index from where to start searching | |
* @example getBetweenBrackets('(',')', 'all_of_this(but((I_want_this)))') | |
* @returns {Array} An array containing [the_match, open_bracket_index, close_bracket_index] | |
*/ | |
function getBetweenBrackets(ob, cb, str, start) { | |
start = start || 0; //defaults to a starting index of zero | |
var l = str.length, | |
open = 0, //the number of open brackets | |
fb; | |
for(var i=start; i<l; i++) { | |
var ch = str.charAt(i); //the current character being looked at | |
if(ch === ob) { | |
if(fb === undefined) fb = i+1;//mark the first bracket found | |
open++; //mark a bracket as open | |
} | |
if(ch === cb) { | |
open--; //close the bracket | |
//if there are no open brackets and there was an open bracket found | |
if(open === 0 && fb !== undefined) { | |
var nb = i; //the closing bracket index is i | |
//return the | |
return [str.substring(fb, nb), fb, nb]; | |
} | |
} | |
} | |
return []; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment