Search code examples
javascriptregexstringsplitparentheses

Split string based on parentheses in javascript


I have a string like below.
Sum(Height(In))

And i need to split above string like this.
Sum
Height(In)

I have tried following regex. But i have no luck.

/[ .:;?!~,`"&|^\((.*)\)$<>{}\[\]\r\n/\\]+/

Is there any way to achieve this?

Thanks in advance.


Solution

  • You can match all up to the first ( and then all between that first ( and the ) that is at the end of the string, and use

    const [_, one, two] = "Sum(Height(In))".match(/^([^()]+)\((.*)\)$/);
    console.log(`The first value is: ${one}, the second is ${two}`);

    See the regex demo. If the last ) is not at the end of string you can remove the $ end of string anchor. If there can be line breaks inside, replace .* with [\w\W]*.

    Regex details:

    • ^ - start of string
    • ([^()]+) - Group 1: one or more chars other than ( and )
    • \( - a ( char
    • (.*) - Group 2: any zero or more chars other than line break chars, as many as possible (* is greedy)
    • \) - a ) char
    • $ - end of string.