다음과 같은 URL이 있습니다.
http://localhost/PMApp/temp.htm?ProjectID=462
내가해야 할 일은 ?
부호 (쿼리 문자열) 다음에 세부 정보를 얻는 것입니다 ProjectID=462
. JavaScript를 사용하여 어떻게 얻을 수 있습니까?
지금까지 내가 한 일은 다음과 같습니다.
var url = window.location.toString();
url.match(?);
다음에 무엇을해야할지 모르겠습니다.
답변
MDN 기사를 살펴 보십시오.window.location
.
QueryString은 window.location.search
.
레거시 브라우저에서도 작동하는 솔루션
MDN 은 QueryString에서 사용할 수있는 단일 키의 값을 가져 오는 방법에 대한 예제 (위의 참조 문서에서 더 이상 사용할 수 없음) 를 제공합니다. 이 같은:
function getQueryStringValue (key) {
return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
// Would write the value of the QueryString-variable called name to the console
console.log(getQueryStringValue("name"));
최신 브라우저에서
최신 브라우저에서는 searchParams
에는 URLSearchParams 객체 를 반환하는 URL 인터페이스 속성이 있습니다. 반환 된 객체에는 get-method를 포함하여 여러 가지 편리한 메서드가 있습니다. 따라서 위의 예와 동일한 것은 다음과 같습니다.
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
그만큼 URLSearchParams의 인터페이스는 쿼리 문자열 형식의 구문 분석 문자열을 사용하고, 편리한 URLSearchParams 객체로 만들어 놓을 수 있습니다.
let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);
searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true
이 인터페이스에서는 브라우저 지원이 여전히 제한되어 있으므로 기존 브라우저를 지원해야하는 경우 첫 번째 예제를 사용하거나 polyfill을 사용 하세요 .
답변
포함window.location.search
후 모든 것을 얻으려면 사용?
?
예:
var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
답변
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})
답변
이것은 queryString 변수에 맵으로 액세스하는 전역 함수를 추가합니다.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
window.location.query = function (source) {
var map = {};
source = source || this.search;
if ("" != source) {
var groups = source, i;
if (groups.indexOf("?") == 0) {
groups = groups.substr(1);
}
groups = groups.split("&");
for (i in groups) {
source = groups[i].split("=",
// For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
(groups[i].slice(-1) !== "=") + 1
);
// Key
i = decodeURIComponent(source[0]);
// Value
source = source[1];
source = typeof source === "undefined"
? source
: decodeURIComponent(source);
// Save Duplicate Key
if (i in map) {
if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
map[i] = [map[i]];
}
map[i].push(source);
}
// Save New Key
else {
map[i] = source;
}
}
}
return map;
}
window.location.query.makeString = function (source, addQuestionMark) {
var str = "", i, ii, key;
if (typeof source == "boolean") {
addQuestionMark = source;
source = undefined;
}
if (source == undefined) {
str = window.location.search;
}
else {
for (i in source) {
key = "&" + encodeURIComponent(i);
if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
str += key + addUndefindedValue(source[i]);
}
else {
for (ii = 0; ii < source[i].length; ii++) {
str += key + addUndefindedValue(source[i][ii]);
}
}
}
}
return (addQuestionMark === false ? "" : "?") + str.substr(1);
}
function addUndefindedValue(source) {
return typeof source === "undefined"
? ""
: "=" + encodeURIComponent(source);
}
}
즐겨.
답변
사용할 일이 있다면 타이프 라이터를 하고있는 DOM 당신의에 LIB 의 tsconfig.json
, 당신은 할 수 있습니다 :
const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');
// To append, you can also leverage api to avoid the `?` check
params.append('newKey', 'newValue');
답변
이 함수는? id =에서 문자열을 분할하는 데 사용할 수 있습니다.
function myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id=");
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");
여기 바이올린입니다
답변
매개 변수 이름을 통해 값을 직접 찾는 데 사용할 수 있습니다.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
