Link to home
Create AccountLog in
Avatar of skij
skijFlag for Canada

asked on

JavaScript/REGEX: Inside a double set of parenthesis

Using JavaScript and Regular Expressions, how can I get the content inside a double set of parenthesis?

getInside2p('http://example.com/dir/(S(u53ouszaxo3dis55xhfm0l45))/page.aspx?xyz'); // should return 'u53ouszaxo3dis55xhfm0l45'
getInside2p('xyz((hello))123'); // should return 'hello'
getInside2p('Hello World'); // should return ''

Open in new window

SOLUTION
Avatar of Rgonzo1971
Rgonzo1971

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of skij

ASKER

Thanks, the REGEX is good, but I get an error if there is no match.

For example,
getInside2p('Hello World'); // should return ''

but that returns an error.

alert(getInside2p('http://example.com/dir/(S(u53ouszaxo3dis55xhfm0l45))/page.aspx?xyz'));
alert(getInside2p('xyz((hello))123'));
alert(getInside2p('hello'));

function getInside2p(str) {
 return(str.match(/\([^\)]*\((.*)\)[^\(]*\)/))[1];
}

Open in new window

The [1] at the end of line 6 is likely causing the error. It is attempting to select the first value of an array that might be generated by the match statement. When there is no match, the match method will return a null value which is not an array, so the [1] designation throws an error. However, this match statement will never return an array, so the [1] designation is unnecessary. In order for the match statement to return an array, the global flag would have to be included in the expression.
Avatar of skij

ASKER

I realize that the problem is cause because of the [1] at the end, however if I don't put that at the end I don't get the desire results.   Please test this, thanks.
alert(getInside2p('http://example.com/dir/(S(u53ouszaxo3dis55xhfm0l45))/page.aspx?xyz'));
alert(getInside2p('xyz((hello))123'));
alert(getInside2p('hello'));

function getInside2p(str) {
 return(str.match(/\([^\)]*\((.*)\)[^\(]*\)/))[1];
}

Open in new window

What are the desired results for your sample code? Are you wanting to limit the match to what is between the inside quotes only, or what is between the double or nested quotes?
Avatar of skij

ASKER

Here are the desired results:

getInside2p('/dir/(S(u53ouszaxo3dis55xhfm0l45))/page.aspx?xyz'); // should return 'u53ouszaxo3dis55xhfm0l45'
getInside2p('xyz((hello))123'); // should return 'hello'
getInside2p('Hello World'); // should return an empty result

I want to limit the match to only what is inside two layers of parenthesis and if there is no match the the result should be empty.
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.