Les*_*ezi 234 javascript parameters url parsing query-string
在使用AJAX调用的Web应用程序中,我需要提交请求,但在URL的末尾添加一个参数,例如:
原始网址:
结果URL:
http://server/myapp.php?id = 10 &enabled = true
寻找一个解析每个参数的URL的JavaScript函数,然后添加新参数或更新值(如果已存在).
Via*_*art 210
您可以使用以下方法之一:
例:
var url = new URL("http://foo.bar/?x=1&y=2");
// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);
// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);
Run Code Online (Sandbox Code Playgroud)
ann*_*ata 180
您需要适应的基本实现看起来像这样:
function insertParam(key, value)
{
key = encodeURI(key); value = encodeURI(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
Run Code Online (Sandbox Code Playgroud)
这大约是正则表达式或基于搜索的解决方案的两倍,但这完全取决于查询字符串的长度和任何匹配的索引
为了完成而我使用慢速正则表达式进行基准测试(大约慢了150%)
function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);
var s = document.location.search;
var kvp = key+"="+value;
var r = new RegExp("(&|\\?)"+key+"=[^\&]*");
s = s.replace(r,"$1"+kvp);
if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};
//again, do what you will here
document.location.search = s;
}
Run Code Online (Sandbox Code Playgroud)
Zoi*_*arp 124
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('order', 'date');
window.location.search = urlParams;
Run Code Online (Sandbox Code Playgroud)
.set 第一个参数是键,第二个参数是值。
小智 63
谢谢大家的贡献.我使用annakata代码并修改为还包括url中根本没有查询字符串的情况.希望这会有所帮助.
function insertParam(key, value) {
key = escape(key); value = escape(value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
document.location.search = '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
}
Run Code Online (Sandbox Code Playgroud)
Meh*_*dız 57
这是非常简单的解决方案.它不控制参数存在,也不改变现有值.它将您的参数添加到end,因此您可以在后端代码中获取最新值.
function addParameterToURL(param){
_url = location.href;
_url += (_url.split('?')[1] ? '&':'?') + param;
return _url;
}
Run Code Online (Sandbox Code Playgroud)
小智 33
这是一个非常简化的版本,为了易读性和更少的代码行而不是微优化的性能进行权衡(我们正在谈论几毫秒的差异,实际上......由于其性质(在当前文档的位置上运行) ),这很可能会在页面上运行一次).
/**
* Add a URL parameter (or changing it if it already exists)
* @param {search} string this is typically document.location.search
* @param {key} string the key to set
* @param {val} string value
*/
var addUrlParam = function(search, key, val){
var newParam = key + '=' + val,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (search) {
// Try to replace an existance instance
params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);
// If nothing was replaced, then add the new param to the end
if (params === search) {
params += '&' + newParam;
}
}
return params;
};
Run Code Online (Sandbox Code Playgroud)
然后你会像这样使用它:
document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');
Run Code Online (Sandbox Code Playgroud)
fre*_*dev 20
/**
* Add a URL parameter
* @param {string} url
* @param {string} param the key to set
* @param {string} value
*/
var addParam = function(url, param, value) {
param = encodeURIComponent(param);
var a = document.createElement('a');
param += (value ? "=" + encodeURIComponent(value) : "");
a.href = url;
a.search += (a.search ? "&" : "") + param;
return a.href;
}
/**
* Add a URL parameter (or modify if already exists)
* @param {string} url
* @param {string} param the key to set
* @param {string} value
*/
var addOrReplaceParam = function(url, param, value) {
param = encodeURIComponent(param);
var r = "([&?]|&)" + param + "\\b(?:=(?:[^&#]*))*";
var a = document.createElement('a');
var regex = new RegExp(r);
var str = param + (value ? "=" + encodeURIComponent(value) : "");
a.href = url;
var q = a.search.replace(regex, "$1"+str);
if (q === a.search) {
a.search += (a.search ? "&" : "") + str;
} else {
a.search = q;
}
return a.href;
}
url = "http://www.example.com#hashme";
newurl = addParam(url, "ciao", "1");
alert(newurl);Run Code Online (Sandbox Code Playgroud)
请注意,参数应在追加到查询字符串之前进行编码.
meo*_*ouw 19
我有一个'类'来做这个,这里是:
function QS(){
this.qs = {};
var s = location.search.replace( /^\?|#.*$/g, '' );
if( s ) {
var qsParts = s.split('&');
var i, nv;
for (i = 0; i < qsParts.length; i++) {
nv = qsParts[i].split('=');
this.qs[nv[0]] = nv[1];
}
}
}
QS.prototype.add = function( name, value ) {
if( arguments.length == 1 && arguments[0].constructor == Object ) {
this.addMany( arguments[0] );
return;
}
this.qs[name] = value;
}
QS.prototype.addMany = function( newValues ) {
for( nv in newValues ) {
this.qs[nv] = newValues[nv];
}
}
QS.prototype.remove = function( name ) {
if( arguments.length == 1 && arguments[0].constructor == Array ) {
this.removeMany( arguments[0] );
return;
}
delete this.qs[name];
}
QS.prototype.removeMany = function( deleteNames ) {
var i;
for( i = 0; i < deleteNames.length; i++ ) {
delete this.qs[deleteNames[i]];
}
}
QS.prototype.getQueryString = function() {
var nv, q = [];
for( nv in this.qs ) {
q[q.length] = nv+'='+this.qs[nv];
}
return q.join( '&' );
}
QS.prototype.toString = QS.prototype.getQueryString;
//examples
//instantiation
var qs = new QS;
alert( qs );
//add a sinle name/value
qs.add( 'new', 'true' );
alert( qs );
//add multiple key/values
qs.add( { x: 'X', y: 'Y' } );
alert( qs );
//remove single key
qs.remove( 'new' )
alert( qs );
//remove multiple keys
qs.remove( ['x', 'bogus'] )
alert( qs );
Run Code Online (Sandbox Code Playgroud)
我已经重写了toString方法,所以不需要调用QS :: getQueryString,你可以使用QS :: toString,或者我在示例中所做的只是依赖于被强制转换为字符串的对象.
Ame*_*icA 14
URL类内部有一个内置函数,您可以使用它来轻松处理查询字符串键/值参数:
const url = new URL(window.location.href);
// url.searchParams has several function, we just use `set` function
// to set a value, if you just want to append without replacing value
// let use `append` function
url.searchParams.set('key', 'value');
console.log(url.search) // <== '?key=value'
// if window.location.href has already some qs params this `set` function
// modify or append key/value in it
Run Code Online (Sandbox Code Playgroud)
有关的更多信息searchParams functions。
Nei*_*ham 11
此解决方案使用更新的搜索参数更新窗口的当前 URL,而无需实际重新加载页面。这种方法在 PWA/SPA 环境中很有用。
function setURLSearchParam(key, value) {
const url = new URL(window.location.href);
url.searchParams.set(key, value);
window.history.pushState({ path: url.href }, '', url.href);
}
Run Code Online (Sandbox Code Playgroud)
如果你有一个带有url的字符串,你想用param装饰,你可以试试这个:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
Run Code Online (Sandbox Code Playgroud)
这意味着什么?将是参数的前缀,但如果你已经有?in urlstring,than &将成为前缀.
encodeURI( paramvariable )如果你没有硬编码参数,我也会建议做,但它在里面paramvariable; 或者如果你有滑稽的角色.
有关该功能的使用,请参阅javascript URL编码encodeURI.
以下功能将帮助您向 URL 或从 URL 添加、更新和删除参数。
//example1and
var myURL = '/search';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
Run Code Online (Sandbox Code Playgroud)
//示例2
var myURL = '/search?category=mobile';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
Run Code Online (Sandbox Code Playgroud)
//示例3
var myURL = '/search?location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
Run Code Online (Sandbox Code Playgroud)
//示例4
var myURL = '/search?category=mobile&location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
Run Code Online (Sandbox Code Playgroud)
//示例5
var myURL = 'https://example.com/search?location=texas#fragment';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california#fragment
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york#fragment
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search#fragment
Run Code Online (Sandbox Code Playgroud)
这是功能。
function updateUrl(url,key,value){
if(value!==undefined){
value = encodeURI(value);
}
var hashIndex = url.indexOf("#")|0;
if (hashIndex === -1) hashIndex = url.length|0;
var urls = url.substring(0, hashIndex).split('?');
var baseUrl = urls[0];
var parameters = '';
var outPara = {};
if(urls.length>1){
parameters = urls[1];
}
if(parameters!==''){
parameters = parameters.split('&');
for(k in parameters){
var keyVal = parameters[k];
keyVal = keyVal.split('=');
var ekey = keyVal[0];
var evalue = '';
if(keyVal.length>1){
evalue = keyVal[1];
}
outPara[ekey] = evalue;
}
}
if(value!==undefined){
outPara[key] = value;
}else{
delete outPara[key];
}
parameters = [];
for(var k in outPara){
parameters.push(k + '=' + outPara[k]);
}
var finalUrl = baseUrl;
if(parameters.length>0){
finalUrl += '?' + parameters.join('&');
}
return finalUrl + url.substring(hashIndex);
}
Run Code Online (Sandbox Code Playgroud)
这是添加查询参数的简单方法:
const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");
Run Code Online (Sandbox Code Playgroud)
这就是更多.
请注意支持规格.
添加到@Vianney的答案/sf/answers/3091265901/
我们可以在node中导入内置的URL模块,如下所示
const { URL } = require('url');
Run Code Online (Sandbox Code Playgroud)
例子:
Terminal $ node
> const { URL } = require('url');
undefined
> let url = new URL('', 'http://localhost:1989/v3/orders');
undefined
> url.href
'http://localhost:1989/v3/orders'
> let fetchAll=true, timePeriod = 30, b2b=false;
undefined
> url.href
'http://localhost:1989/v3/orders'
> url.searchParams.append('fetchAll', fetchAll);
undefined
> url.searchParams.append('timePeriod', timePeriod);
undefined
> url.searchParams.append('b2b', b2b);
undefined
> url.href
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
> url.toString()
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
Run Code Online (Sandbox Code Playgroud)
有用的链接:
https://developer.mozilla.org/en-US/docs/Web/API/URL https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
这是我自己的尝试,但我会使用 annakata 的答案,因为它看起来更清晰:
function AddUrlParameter(sourceUrl, parameterName, parameterValue, replaceDuplicates)
{
if ((sourceUrl == null) || (sourceUrl.length == 0)) sourceUrl = document.location.href;
var urlParts = sourceUrl.split("?");
var newQueryString = "";
if (urlParts.length > 1)
{
var parameters = urlParts[1].split("&");
for (var i=0; (i < parameters.length); i++)
{
var parameterParts = parameters[i].split("=");
if (!(replaceDuplicates && parameterParts[0] == parameterName))
{
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterParts[0] + "=" + parameterParts[1];
}
}
}
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterName + "=" + parameterValue;
return urlParts[0] + newQueryString;
}
Run Code Online (Sandbox Code Playgroud)
另外,我从 stackoverflow 上的另一篇文章中找到了这个 jQuery 插件,如果您需要更大的灵活性,可以使用它:http : //plugins.jquery.com/project/query-object
我认为代码将是(尚未测试):
return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
Run Code Online (Sandbox Code Playgroud)
查看https://github.com/derek-watson/jsUri
Uri和javascript中的查询字符串操作。
该项目包含了Steven Levithan出色的parseUri正则表达式库。您可以安全地解析各种形状和大小的URL,但是这些URL无效或令人生厌。
有时我们?在最后的URL 看到,我发现了一些产生结果的解决方案file.php?&foo=bar.我按照自己的意愿完成了自己的解决方案工作!
location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'
Run Code Online (Sandbox Code Playgroud)
注意:location.origin在IE中不起作用,这是它的修复.
它处理这样的 URL:
?,但同时没有任何参数它不处理这样的 URL:
工作于:
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = (parameters + name + "=" + value);
return (parsedURL.origin + parsedURL.pathname + parameters);
}
Run Code Online (Sandbox Code Playgroud)
带有 ES6 模板字符串的版本。
工作于:
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = `${parameters}${name}=${value}`;
return `${parsedURL.origin}${parsedURL.pathname}${parameters}`;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
尝试这个。
// uses the URL class
function setParam(key, value) {
let url = new URL(window.document.location);
let params = new URLSearchParams(url.search.slice(1));
if (params.has(key)) {
params.set(key, value);
}else {
params.append(key, value);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
506463 次 |
| 最近记录: |