Extracting data from string by splitting URL twice - javascript

I would like to achieve the following:
I have a URL: https://www.example.com/Place/Name.html?randomtext
I need to return "Name" only on outgoing links.
I thought it would work by doing the following:
function() {
if ({{outgoing link}})
var Name= {{Click URL}};
return Name.split("/")[2];
return Name.split("?")[0];
}
I already managed to get "place" by doing:
function() {
if ({{outgoing link}})
var Name= {{Click URL}};
return Name.split("/")[2];

One way to get the filename ("Name") would be to do:
var filename = url.substring(url.lastIndexOf('/')+1).split(".")[0]
https://codesandbox.io/s/magical-roman-uerpcp?file=/src/index.js

not sure if this is what u want:
const url = 'https://www.example.com/Place/Name.html?randomtext'
function extractSliceFromUrl() {
return url.split("/")[4].split(".")[0];
}
const url = 'https://www.example.com/Place/Name.html?randomtext'
function extractSliceFromUrl() {
return url.split("/")[4].split(".")[0];
}
console.log(extractSliceFromUrl(url))
console.log(extractSliceFromUrl(url))

Related

how can I use a variable value to define a new variable in JavaScript? [duplicate]

This question already has an answer here:
using variable results (contents) to create new variables
(1 answer)
Closed 10 months ago.
I have a list
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
how can I use these peoples numbers if their names matches another variable result?
We have
var name = *selected server-side student names*
and by these * signs I mean it's a great list that name gives up but it only gives up one name out of that list at the time we call it.
If one of these students is selected by name variable, how can I use the number defined in front of that name in const StudentCode to generate a url?
Suppose you get Rose! Then the number for Rose is: 35621548 and the url for example will be https://www.35621548.com. What code can we use to generate this url for example in console?
console.log(url)
Use this:
if (StudentCode.hasOwnProperty(name){
const url = `https://www.${StudentCode[name]}.com`
}
This function will return you the url on the basis of the student name that is passed in this function.
function returnURL(studentName){
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
if (!!!StudentCode[studentName]) return "";
return "https://" + StudentCode[studentName] + ".com";
}
console.log(returnURL("Rose"));
Hope, this helps!!
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
let studentName = "Jack"
const url = `https://${StudentCode[studentName]}.com`
console.log(url)
export const studentUrlModule = (function() {
const studentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const url = 'https://$code.com'
const generateUrl = function(code = '') {
if (!url) {
throw new Error('Url is not defined')
} else if (!code) {
throw new Error('Code is not defined')
};
return url.replace('$code', `${code}`);
}
function getCode(name = '') {
const code = studentCode[name];
if (!code) {
throw new Error(`There is no code with name(${name}).`);
}
return code;
}
function getUrl(name = '') {
if (!name) {
throw new Error('StudentName is undefined')
};
const code = getCode(name);
const studentUrl = generateUrl(code);
return studentUrl;
}
return {
generateUrl,
getCode,
getUrl,
};
}());
Maybe it helps. If the code was not founded then it throws an error. Please use try, catch error handlers to handle errors.
-- Update
I updated the code and as you can see it's a module and you need to import it everywhere you like to use this.
if you are not familiar with modules and how to use them inside the browser check documents.
Mozila documents
Super Simple Start to ESModules in the Browser

How do I trim/strip URL down to get specific data?

How would I go about trimming/stripping the URL down to get specific data...
So: https://www.example.com/items/423455344/size-39
Would become: 423455344
Any ideas?
If you know the URL is always going to match that format, you could do something like this.
function getData() {
let foo = window.location.href.split("/"); //this gives you an array with the data between the slashes
let searchController = "items"; //this is the key before the data you need
for (let i=0; i<foo.length; i++){
if (foo[i] === searchController){
searchController = "/true/";
} else if (searchController === "/true/") {
return foo[i];
}
}
}
Let me know if you have any questions

how to send ids of object to backend funtion?

My knowledge of front end it is not so good, and I don't know how to send array of ids to back end which will get all data and will be open it into new page. pls help
there my function:
#has_session_params('tin')
def print_documents(request):
doc_ids = request.POST.getlist('doc_ids[]')
tin = request.session['tin']
params = dict()
template = 'documents/documents_to_print.html'
params['Docs'] = docs
params['pb'] = pb
params['is_pdf'] = request.GET.get('is_pdf', 'false')
params['host'] = request.scheme + "://" + request.META["HTTP_HOST"]
params['url'] = settings.SITE_URL + request.get_full_path()
params['doc_type'] = INVOICE_TYPE
invoice_list = list()
for doc_id in doc_ids:
response = proxy.get_invoice_by_id(invoice_id=doc_id, tin=tin)
if response.status.code != pb.ResponseStatus.OK:
response = proxy.get_invoice_draft_by_id(
invoice_draft_id=doc_id, tin=tin)
invoice_list.append(response.invoice)
params['invoices'] = invoice_list
return render(request, template, params)
I know how to get one object by id, it will be like:
def print_document(request, doc_id):
and something like that, and where url for function will be look like that:
url(r'^print_documents/(?P<doc_id>[a-z\d]{24})/$', invoices.print_documents, name='print_documents')
and new page link will be like that localhost:8000/documents/print_documents/{doc_id}
and this method I can just call like :
print
but now I want to select several documents and send doc_ids, and I know that I can to like method above but I don't want big link. And how I can send array of ids to back end correctly?
now I have something like that:
printAll.on("click", function(){
var invoicesID = [];
$('input.select-inv-check:checked').each(function() {
invoicesID.push($(this).data('docid'));
});
var url = Globals.printAll;
$.post( url, { doc_ids: invoicesID } ).done(function(result) {
console.log("result", result[0].Docs);
if(result.code == 0){
}else{
alert(result.message);
}
});
});
And I know that it doesn't correct! pls help

How to properly add search query param to url containing hash in javascript?

I want to add a base url and query parameters to each link:
function buildURL(relativePath) {
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
return url.toString();
}
It works fine for most cases:
buildURL('search')
"http://example.com/search?utm_source=app"
buildURL('search?q=query&page=2')
"http://example.com/search?q=query&page=2&utm_source=app"
The problem starts when I add an anchor:
buildURL('search#anchor')
"http://example.com/search?utm_source=app#anchor"
buildURL('search#anchor?q=query')
"http://example.com/search?utm_source=app#anchor?q=query"
This is not a valid URL with an anchor.
Any ideas on how to overcome that using URL?
EDIT
The expected outcome is adding the query params after the anchor
buildURL('search#anchor')
"http://example.com/search#anchor?utm_source=app"
buildURL('search#anchor?q=query')
"http://example.com/search#anchor?utm_source=app?q=query"
function buildURL(relativePath) {
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
Don't pass in a hash in the search params.
But if you must, you can detect the hash, split it from the parameter, set the search param and add the hash
function buildURL(relativePath) {
var hash = "";
if (relativePath.indexOf("#")!=-1) {
var parts = relativePath.split("#");
hash = encodeURIComponent(parts[1]); // optionally handle ? in the hash part
relativePath=parts[0];
}
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
if (hash) url.hash=hash;
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
This should work.. Pass the hash after the query params
function buildURL(path) {
var relativePath = path.split('#')
var url = new URL('http://example.com/' + relativePath[0]);
url.searchParams.set('utm_source', 'app');
url.hash = relativePath[1] ? relativePath[1] : ''
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
console.log(buildURL("searchr?q=query&q2=query2#anchor"));

Change route values of a link with jQuery

I'd appreciate any help.
I'm trying to change the link href each time with Kendo Grid change() event:
function ContractsGrid_onChange(e) {
var selected = this.select()[0],
item = this.dataItem(selected);
$('#createOnBase').attr('href', function () {
var createLink = document.getElementById("createOnBase");
var route = 'http://' + createLink.hostname + createLink.pathname + "?contractID =" + item.ID;
return route;
});
}
#Ajax.ActionLink("Create", "CreateOnBase",
new { contractID = "_contractID_" },
new AjaxOptions() {... },
new { id="createOnBase" })
I'm not sure with current approach, because i have different hostnames (localhost with port or server domain)
The best way would be:
var route = "#Url.Action('CreateOnBase', new { contractID = ??})";
But I cannot use JS variable (item.ID) in razor.
Also, this.href.replace("_contractID_", item.ID) won't work for several changes.
Can you help me with another solution?
Thanks a lot!
Yeh, that was easy, I found a way:
$('#createOnBase').attr('href', function () {
return "#Url.Action("CreateOnBase")"+ "/?contractID=" +item.ID;
});
maybe it will be helpful for someone.
The first thought that come up to my mind is to store root url in separate variable.Something like this:
function ContractsGrid_onChange(e) {
var selected = this.select()[0],
item = this.dataItem(selected);
var rootUrl = #Url.Action("Create", "CreateOnBase");
$('#createOnBase').attr('href', function () {
var createLink = document.getElementById("createOnBase");
var route = rootUrl + "?contractID =" + item.ID;
return route;
});
}
This is just a workaround, not sure about some advanced way...

Categories