Take url variable with regex

I have the following url

http://www.test.info/link/?url=http://www.site2.com 

How to get url parameter value with regular expressions in javascript?

thanks

+4
source share
5 answers
 function extractUrlValue(key, url) { if (typeof(url) === 'undefined') url = window.location.href; var match = url.match('[?&]' + key + '=([^&]+)'); return match ? match[1] : null; } 

If you are trying to match the "url" from the page the visitor is currently on, you will use this method as follows:

 var value = extractUrlValue('url'); 

Otherwise, you can pass your own url like

 var value = extractUrlValue('url', 'http://www.test.info/link/?url=http://www.site2.com 
+6
source

Check out http://rubular.com to check for regex:

 url.match(/url=([^&]+)/)[1] 
+9
source

You can check it out: http://snipplr.com/view/799/get-url-variables/ (works without regEx)

In this case, regEx is used: http://www.netlobo.com/url_query_string_javascript.html

 function gup( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return results[1]; } var param = gup( 'var' ); 
+3
source

Ok, first of all, what is the entire query string? If so, all you have to do is split by: =

 url.split('=')[1]; 

Otherwise, you can use Jordan Regex.

+1
source

In the response code:

 function extractUrlValue(key, url) { if (typeof(url) === 'undefined') url = window.location.href; var match = url.match('[?&]' + key + '=([^&#]+)'); return match ? match[1] : null; } 

If key is the last parameter in the URL, and after that there is an anchor - it enters the code, return value#anchor as the value. # in regexp '[?&]' + key + '=([^&#]+)' prevent this.

0
source

Source: https://habr.com/ru/post/1342888/


All Articles