我有两个字符串: str1是具有属性
的控制器的URLstr1 = /Controller/Action?tableid=212&id=&someOtherVal=false
和str2是在字段中更改后,'id ='为str1后应添加的id值。
如何在str1中'id ='之后添加此ID,例如'123'?
答案 0 :(得分:1)
我希望下面的代码段是您所期待的
var str1 = "/Controller/Action?tableid=212&id=&someOtherVal=false";
// location.protocol + location.hostname is just to complete the URL
var urltoedit = new URL(location.protocol + location.hostname + str1);
var str2 = 123;
// check if id has value or you can modify if your condition
if(urltoedit.searchParams.get("id")=="")
{
urltoedit.searchParams.set("id",str2);
}
// valtoset is what you need
var valtoset = urltoedit.pathname+urltoedit.search;
答案 1 :(得分:0)
您只需使用替换:
var val = '123';
var str1 = '/Controller/Action?tableid=212&id=&someOtherVal=false'.replace('&id=','&id='+val);
console.log(str1);
如果你确定{& id
之后的&
将会存在,那么这将是完美的。此外,您不能简单地使用replace('id=','&id=123');
,因为您看到字符串tableid=
将与此匹配,123
的值tableid
将替换为tableid=123
,它变为id
}
对于备份,如果您认为 var val = '123';
var str1 = '/Controller/Action?tableid=212&id=&someOtherVal=false'.replace('&id=','&id='+val).replace('?id=','&id='+val);
console.log(str1);
将位于查询字符串的开头,那么您可以执行此操作:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var photoURL = user.photoURL;
} else {
// User is not logged in, redirect to where you need to.
console.log("Logged out");
}
答案 2 :(得分:0)
如果id是第一个或最后一个参数,并且id已经有值,则需要处理。 这是解决方案:
var url = "/Controller/Action?tableid=212&id=rrr&someOtherVal=false";
var parameterName = "id";
var value = "123";
function replaceParameterValueInUrl(url, parameter, value){
var parameterStart1 = "&" + parameter + "=";
var parameterStart2 = "?" + parameter + "=";
//Is first parameter in URL?
var parameterStart = url.indexOf(parameterStart1) === -1 ? parameterStart2 : parameterStart1;
var parameterEnd = "&";
var startIndex = url.indexOf(parameterStart);
var endIndex = url.substring(startIndex + parameterStart.length).indexOf(parameterEnd);
//Is last parameter of URL?
if(endIndex === -1) endIndex = 0;
var searchIndex = startIndex + endIndex;
return url.substring(0, startIndex + parameterStart.length) + value + (endIndex === 0 ? "" : url.substring(searchIndex + parameterStart.length));
}
//Usage:
var replaced = replaceParameterValueInUrl(url, parameterName, value);