skij
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 ''
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
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.
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];
}
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?
ASKER
Here are the desired results:
getInside2p('/dir/(S(u53ou szaxo3dis5 5xhfm0l45) )/page.asp x?xyz'); // should return 'u53ouszaxo3dis55xhfm0l45'
getInside2p('xyz((hello))1 23'); // 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.
getInside2p('/dir/(S(u53ou
getInside2p('xyz((hello))1
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
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
For example,
getInside2p('Hello World'); // should return ''
but that returns an error.
Open in new window