Feeling a bit generous today, here's a unique example I came up with just for you:
// This function takes a string and converts it into an array representing the grouping symbols in the string
function parseString(str)
{
// Trim any leading or trailing whitespace from the input string
str = str.trim();
// Split the string into an array of individual characters
var arr = str.split('');
// Initialize an array to store matched parts of the string
var parsed = [];
// Keep track of the current level of parenthesis nesting
var parentheses = 0;
// Create an array to represent each level of parentheses
var levels = [parsed];
// Shortcut to access the array for the current parentheses level
var current = parsed;
// Filter out any operators not intended for checks
var notOperators = /^[ ()]*(.*?)[ ()]*$/;
// Count occurrences of a substring in the string
function count(arg, substring) { return arg.split(substring).length; };
// Check if there are an equal number of opening and closing parentheses
if (count(str, '(') !== count(str, ')')) throw new SyntaxError('Unmatched parentheses');
// Add the word before an operator/space, if applicable
function addPart()
{
// Remove already parsed parts and get the word
var beginning = arr.splice(0, i).join('').trim();
// Remove any operator tokens
var str = beginning.match(notOperators)[1];
if (str) current.push(str);
// Reset the loop counter after parsing a part of the string
i = 0;
}
// Loop through each character in the input string
for (var i = 0; i < arr.length; ++i)
{
var token = arr[i];
// Handle spaces between words
if (token === ' ') addPart();
// Open a new grouping symbol
else if (token === '(')
{
addPart();
// Add a new level of hierarchy and update the reference
current.push([]);
current = levels[++parentheses] = current[current.length - 1];
}
// Close an open grouping symbol
else if (token === ')')
{
addPart();
// Move one level up the hierarchy of parentheses
current = levels[--parentheses];
}
// Ensure no invalid instances like "a)(" are present
if (parentheses < 0) throw new SyntaxError('Unexpected token )');
}
// Add the final word before the end of the string
addPart();
// Return the array that represents the string
return parsed;
}
Just for your clarity, consider this example:
parseString('The (quick) brown (fox (jumps)) (over the) lazy (dog)');
This will output:
["The", ["quick"], "brown", ["fox", ["jumps"]], ["over", "the"], "lazy", ["dog"]]