I'm pretty new to JS and I've been reading online tutorials to get the hang of it. I usually don't go forward on the tutorials until I understand everything of what I'm learning and right now I'm stuck at trying to understand and figure out how Regex patterns work...
So, I was reading THIS cookies tutorial and I got stuck at one point...
On the function to retrieve the cookies from the visitor's computer, they use a matching function that tries to get the value of the cookie...
function get_cookie ( cookie_name )
var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
if ( results )
return ( unescape ( results ) );
I have a few questions.
1. Why is the Regular Expression in a single quote instead of the '/'?
2. about the Regex patterns... I don't understand why they use the vertical bar in both groups (^|? and (;|$)... after a lot of thought and research I kinda figured out that they are trying to search for a semi colon that marks the beginning of the name of each cookie stored on the document.cookie but if they don't find it it's alright since it means it's the beginning of the document. And the same at the end of the line/document. But still I don't understand why they use the vertical bar if they're not trying to find two values...
I used a Regex tester online and tried to erase the vertical bars, but it stopped matching the cookie string. So I'm just really confused. I know what the pattern does but I don't understand exactly how it's working.
Hope I was clear enough! English is not my mother language so I apologize if this was unclear or hard to read. But please help me