How to get regex with replace method? In my case I've got string which uses char / between.
input:
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem + "/mc/" + mainCategory + "/sc/" + subCategory + "/ty/" + type;
output:
"cn/Nemesis Group/st/2/ic/null/pr/1 - High/es/null/mc/Add/Button/sc/Core/Label/ty/str"
variable mainCategory and subCategory returns string 'Add/Button' and 'Core/Label'
How to replace 'Add/Button' to 'Add%2FButton' and 'Core/Label' to 'Core%2FLabel' without changing any other char?
string.replace("\/", "%2F")
will change all char / to %2F
You can use encodeURIComponent() and decodeURIComponent() to transform this String
Example:
const companyName = "Company",
state = "State",
incCi = "IncCi",
priority = "Priority",
emplSystem = "EmplSystem",
mainCategory = 'Add/Button',
subCategory = 'Core/Label',
type = "Type";
var string = "cn/" + companyName + "/st/" + state + "/ic/" + incCi + "/pr/" + priority + "/es/" + emplSystem +
"/mc/" + encodeURIComponent(mainCategory) +
"/sc/" + encodeURIComponent(subCategory) + "/ty/" + type;
console.log(string)
It sounds to me like you are looking to encode the url. You can use encodeURI in JS to encode a url.
let encodedURL = encodeURI(url);
You can read more about it here.
If you want to encode the string altogether without ignoring any domain related parts, you can us encodeURIComponent()
let encodedURL = encodeURIComponent(url);
You can read more about their differences here.
EDIT:
If you are not encoding a url and you just want to repalce / with %2F only in mainCategory and subCategory then you need to run the regex on the string itself before joining them.
var string = "cn/" + companyName +
"/st/" + state +
"/ic/" + incCi +
"/pr/" + priority +
"/es/" + emplSystem +
"/mc/" + mainCategory.replace("\/", "%2F") +
"/sc/" + subCategory.replace("\/", "%2F") +
"/ty/" + type;
Related
I need to send a http request to firebase that has this shape
https://db.firebaseio.com/0.json?&orderBy="name"&startAt=query&endAt=query+"\uf8ff"&limitToLast=1&print=pretty&auth=auth_token
My problem is that when I call this request I've a 400 error in console because it replace %22 to question marks and other symbols for \uf8ff and I think firebase doesn't recognize that.
let name = '"name"';
let cod = '"\uf8ff"';
let url = ('https://db.firebaseio.com/0.json?&orderBy=' + encodeURIComponent(name) + '&startAt=' + encodeURIComponent(birraName) + '&endAt=' + encodeURIComponent(birraName) + '+' + encodeURIComponent(cod) + '&limitToLast=1&print=pretty&auth=' + encodeURIComponent(this.idToken));
let response = this.http.get(url).map(res => res.json());
return response;
And then in console
400 Bad Request
Do you have any thougths?
You're missing quotes in your target string to mark string values. If you're searching for nodes starting with Marco, it should be https://db.firebaseio.com/0.json?&orderBy="name"&startAt="Marco"&endAt="Marco\uf8ff"&limitToLast=1&print=pretty&auth=auth_token. Note the double quotes around "Marco" and "Marco\uf8ff".
To build these in your JavaScript:
var url = 'https://db.firebaseio.com/0.json';
url = url + '?orderBy="' + encodeURIComponent(name) + '"';
url = url + "&startAt="' + encodeURIComponent(birraName) + '"';
url = url + "&endAt="' + encodeURIComponent(birraName) + '\uf8ff"';
url = url + '&limitToLast=1&print=pretty';
url = url + '&auth="' + encodeURIComponent(this.idToken))+'"";
Template literals might also be useful to keep this readable:
let url = (`https://db.firebaseio.com/0.json?orderBy=${encodeURIComponent(name)}&startAt=${encodeURIComponent(birraName)}&endAt=${encodeURIComponent(birraName)}${encodeURIComponent(cod)}&limitToLast=1&print=pretty&auth=${encodeURIComponent(this.idToken))}`;
I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}
I am working on VS2103 Cordova App. I have created list of items. I want to pass data to another page when i press on item. I've created this list by jQuery.
Here is my code :
for (var i = 0; i < data.length; i++) {
if ((Provider == "Doctors")) {
$("#list").append('<li class="list-message" ><a class="w-clearfix w-inline-block" href="javascript:ProviderDetails(' + data[i].DoctorName + ',' + data[i].DoctorAddress + ',' + data[i].DoctorPhone + ',' + data[i].DoctorPhone2 + ',' + data[i].DoctorPhone3 + ',' + data[i].DocLat + ',' + data[i].DocLong + ',' + data[i].DoctorNotes + ',' + data[i].Category + ');" data-load="1"><div class="w-clearfix column-left"><div class="image-message"><img src="images/Doctors.png"></div></div><div class="column-right"><div class="message-title">' + data[i].DoctorName + '</div><div class="message-text">' + data[i].DoctorAddress + '</div></div></a></li>');
}
}
And here is my function :
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category) {
localStorage.setItem("Name", Name);
localStorage.setItem("Address", Address);
localStorage.setItem("Tel", Tel);
localStorage.setItem("Phone2", Phone2);
localStorage.setItem("Phone3", Phone3);
localStorage.setItem("Lat", Lat);
localStorage.setItem("Lang", Lang);
localStorage.setItem("Notes", Notes);
localStorage.setItem("Category", Category);
window.location.href = "../Details.html";
}
It doesn't do any thing when i press any items . Any help ?
Pay attention on how you build the string:
href="javascript:ProviderDetails(' + data[i].DoctorName + ',' ......
you need to add the string delimiters:
href="javascript:ProviderDetails(\'' + "data[i].DoctorName" + '\',\'' .....
Your function is declared as:
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category)
{
....
}
Now, because your function expects strings as input you can call your function as:
ProviderDetails('string1', 'string2', .....)
Your javascript loop instead produces:
ProviderDetails(string1, string2, .....)
For javascript now the parameters are considered as variables, i.e., string1 is no more a string but a value contained in the variable string1.
But because you do not have such a variable your function call does not work.
So, the delimiters are important to instruct js to understand the beginning and end of a string.
As a delimiter you can you the symbols: ' or ".
But you need to escape the delimiter itself if you want to use it inside the strings:
var a = 'this isn't a string'; // wrong because the inner delimiter is not escaped.
var a = 'this isn\'t a string'; // OK because the inner delimiter is escaped
Of course if you use inside the string the other delimiter you do not need to escape it.
var a = "this isn't a string"; // this is OK
I am using prototype in my application but I am not sure how to add this correctly. Basically I have the following function and I need to construct the href of an anchor from which I already have the reference to a series of appended values
MyJavascriptClass.prototype.init = function() {
this.ToDate = $(this.Prefix + 'ToDate');
this.FromDate = $(this.Prefix + 'FromDate');
}
so in the following function I need to add those as parameters in the url attribute
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=7/18/2012&EndDate=1/19/2012');
}
How can i do something like 'MyWebPage.aspx?StartDate=this.ToDate&EndDate=this.FromDate' ? Any help would be appreciated.
If you are using jquery, and $(this.Prefix + 'ToDate') and $(this.Prefix + 'FromDate') represent fields that contain values, then you can do this:
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=' + this.ToDate.val() + '&EndDate=' + this.FromDate.val() + '');
}
It is difficult to tell from your code what they represent, and why you have them wrapped in $(..).
If ToDate and FromDate contain the two date values, then this should work...
'MyWebPage.aspx?StartDate=' + this.ToDate + '&EndDate=' + this.FromDate
If you don't know every properties:
var properties = [];
for(var i in this)
if(this.hasOwnProperty(i))
properties.push(i+'='+this[i]);
var url = 'MyWebPage.aspx?'+properties.join('&');
var string = "My name is: ",
name = "Bob",
punctuation = ".",
greeting = string + name + punctuation;
Or
var User = { name : "Bob", age : 32, sign : "Leo" },
welcome = "Hi, I'm " + User.name + ", and I'm " + User.age + " years old, I'm a " + User.sign + ", and I enjoy long walks on the beach.";
Here are some strings that I'm using to ultimately form a HTML mailto link. I'm doing this in javascript. If I output the mailtoString to an alert() I get the link looks just fine. However, when I put it into the location.href the string is cut short at the "&" character. How do I tell the location.href that the "&" is not the end of the mailto link?
var subject = escape('subject');
var body = escape('body');
var reportUrl = document.URL + "/GetUpdatedTableResults?beginDate=" + beginDate + "&endDate=" + endDate + "&fileId=" + DocId + '&languageCode=' + LangCode + '&documentResultType=' + result + '&result=' + ReportedIssue;
var excelUrl = document.URL + 'CurReport/GetCSVReport?beginDate=' + beginDate + '&endDate=' + endDate + '&fileId=' + DocId + '&languageCode=' + LangCode + '&documentResultType=' + result + '&result=' + ReportedIssue;
var mailtoString = 'mailto:?subject=' + subject + '&body=' + body + '%0A%0AWeb:%0A' + reportUrl + '%0A%0AExcel:%0A' + excelUrl;
location.href = mailtoString;
After running the code above I get the following output.
http://localhost:5050/CurReport/GetUpdatedTableResults?beginDate=0
Because immediately after mailto: should be the email address. ? is a valid email characters but & is not. Anyway, the & should be escaped to &.