JavaScript에서 URL 구문 분석
JavaScript (jQuery 포함)로 URL을 어떻게 구문 분석합니까?
예를 들어 문자열에 이것을 가지고 있습니다.
url = "http://example.com/form_image_edit.php?img_id=33"
나는 가치를 얻고 싶다 img_id
나는 PHP로 쉽게 할 수 있다는 것을 알고 parse_url()
있지만 JavaScript로 어떻게 가능한지 알고 싶습니다.
a
요소 를 만들고 URL을 추가 한 다음 Location 객체를 사용하는 트릭을 사용할 수 있습니다 .
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
parseUrl('http://example.com/form_image_edit.php?img_id=33').search
다음을 출력합니다. ?img_id=33
php.js 를 사용 하여 JavaScript 에서 parse_url 함수 를 가져올 수도 있습니다 .
업데이트 (2012-07-05)
매우 간단한 URL 처리 이상을 수행해야하는 경우 우수한 URI.js 라이브러리를 사용하는 것이 좋습니다 .
당신의 문자열을 호출하는 경우 s
다음
var id = s.match(/img_id=([^&]+)/)[1]
당신에게 줄 것입니다.
이 시도:
var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]
Existing good jQuery plugin Purl (A JavaScript URL parser). 이 유틸리티는 jQuery를 사용하거나 사용하지 않고 두 가지 방법으로 사용할 수 있습니다.
Google에서 가져 왔습니다.이 방법을 사용해보십시오.
function getQuerystring2(key, default_)
{
if (default_==null)
{
default_="";
}
var search = unescape(location.search);
if (search == "")
{
return default_;
}
search = search.substr(1);
var params = search.split("&");
for (var i = 0; i < params.length; i++)
{
var pairs = params[i].split("=");
if(pairs[0] == key)
{
return pairs[1];
}
}
return default_;
}
짧막 한 농담:
location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})
이것은 kobe의 답변에서 몇 가지 가장자리 사례를 수정해야합니다.
function getQueryParam(url, key) {
var queryStartPos = url.indexOf('?');
if (queryStartPos === -1) {
return;
}
var params = url.substring(queryStartPos + 1).split('&');
for (var i = 0; i < params.length; i++) {
var pairs = params[i].split('=');
if (decodeURIComponent(pairs.shift()) == key) {
return decodeURIComponent(pairs.join('='));
}
}
}
getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"
javascript url 구문 분석 라이브러리 인 URL.js 를 작성했습니다.이를 위해 사용할 수 있습니다.
예:
url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"
이와 같은 것이 당신을 위해 일할 것입니다. 여러 쿼리 문자열 값이 있더라도이 함수는 원하는 키 값을 반환해야합니다.
function getQSValue(url)
{
key = 'img_id';
query_string = url.split('?');
string_values = query_string[1].split('&');
for(i=0; i < string_values.length; i++)
{
if( string_values[i].match(key))
req_value = string_values[i].split('=');
}
return req_value[1];
}
jquery 플러그인 http://plugins.jquery.com/url을 사용할 수 있습니다 . $.url("?img_id")
돌아올 것이다33
function parse_url(str, component) {
// discuss at: http://phpjs.org/functions/parse_url/
// original by: Steven Levithan (http://blog.stevenlevithan.com)
// reimplemented by: Brett Zamir (http://brett-zamir.me)
// input by: Lorenzo Pisani
// input by: Tony
// improved by: Brett Zamir (http://brett-zamir.me)
// note: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
// note: blog post at http://blog.stevenlevithan.com/archives/parseuri
// note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
// note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
// note: a seriously malformed URL.
// note: Besides function name, is essentially the same as parseUri as well as our allowing
// note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
// example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
// returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
var query, key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',
'relative', 'path', 'directory', 'file', 'query', 'fragment'
],
ini = (this.php_js && this.php_js.ini) || {},
mode = (ini['phpjs.parse_url.mode'] &&
ini['phpjs.parse_url.mode'].local_value) || 'php',
parser = {
php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
};
var m = parser[mode].exec(str),
uri = {},
i = 14;
while (i--) {
if (m[i]) {
uri[key[i]] = m[i];
}
}
if (component) {
return uri[component.replace('PHP_URL_', '')
.toLowerCase()];
}
if (mode !== 'php') {
var name = (ini['phpjs.parse_url.queryKey'] &&
ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
uri[name] = {};
query = uri[key[12]] || '';
query.replace(parser, function($0, $1, $2) {
if ($1) {
uri[name][$1] = $2;
}
});
}
delete uri.source;
return uri;
}
var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]
나를 위해 일했습니다. 그러나 첫 번째 변수는 var url = window.location.href 여야합니다.
웹 작업자는 URL 구문 분석을위한 유틸리티 URL 을 제공합니다 .
참고URL : https://stackoverflow.com/questions/6644654/parse-an-url-in-javascript
'IT TIP' 카테고리의 다른 글
PHP-부동 숫자 정밀도 (0) | 2020.10.15 |
---|---|
GNU 화면이 응답하지 않고 차단 된 것 같습니다. (0) | 2020.10.15 |
const 객체를 반환해야합니까? (0) | 2020.10.15 |
업데이트 된 APK를 수동으로 설치하면 '서명이 이전에 설치된 버전과 일치하지 않습니다.'와 함께 실패합니다. (0) | 2020.10.15 |
HTTPClient 응답에서 GZip 스트림 압축 해제 (0) | 2020.10.15 |