Getting out a product ID from URL - JavaScript - javascript

I'm trying to catch only a product ID from a URL. The ID is broke into 2 pieces:
https://www.example.org/category/first_part_of_ID-some_text-second_part_of_id
I was stuck with this function
var ft = "ft_";
var pod = "_";
var pageUrl = window.location.href;
var pageUrl1 = pageUrl.split("-")[1];
var pageUrl2 = pageUrl.replace("/","");
return pageUrl2;
}
Can anyone please help me clearing out everything except for the numbers? I tried with 2 different functions and putting it together, but it also didn't work.

This answer assumes the id you are trying to extract will always follow /category/ in the URL as well as that the first and second parts of the id always be located between the -some_text- part of the url
const url = window.location.href;
const urlAfterCategory = url.split('/')[4];
const id = `${urlAfterCategory.split('-')[0]}${urlAfterCategory.split('-')[2]}`
console.log(id); // Your id

Related

How to insert dynamic URL parameters in HTML (Javascript)

I'm working on a marketing landing page that would take parameters in a URL and then display them in the HTML of an id on the page. Right now, I have every text placeholder defined in addition to each parameter from the URL.
The code below is working fine, but is there a way to remove the redundancies so that if any id matches the name of a parameter in the URL (e.g. a span has id "city" is automatically matched with the parameter "city"), they recognize and update the inner HTML? Thanks for any help.
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const company_text = document.getElementById("company");
const company = urlParams.get('company');
if (company != null){
company_text.innerHTML = company;
}
const city_text = document.getElementById("city");
const city = urlParams.get('city');
if (city != null){
city_text.innerHTML = city;
}
Edited to update parameter names for clarity
You could put something like this at the end of your page
for(const [id, val] of urlParams.entries()) {
const htmlElement = document.getElementById(id);
if(htmlElement) {
htmlElement.innerHTML = val;
}
}
Keep in mind that the same parameter can appear more than one time in the query string (e.g. ?x=1&x=2). In that case there will be two entries with the same id.
Ref for entries.
This can be done by iterating over a list of all URL parameters and changing the HTML content of elements with the correct IDs.
var parameters = new URLSearchParams(window.location.search);
for (const parameter of parameters) {
document.querySelectorAll(`[id=${parameter[0]}]`).forEach(element => {
element.innerHTML = parameter[1];
});
}
I hope this solves your problem.
Best Regards,

How to search and replace elements from one URL to make a new one?

On my site, I want to search/replace for all instances of one URL (that has different IDs, otherwise it is the same) to another.
For example, my site could have the following hyperlinked URLs (they are just examples, again, the IDs will be different):
https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=7
https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=35
https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=100
https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=9434
and so I would want the new URLs to be
https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=7&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO
https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=35&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO
https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=100&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO
https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=9434&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO
I am using the following JavaScript code to achieve what I want in the HTML that follows, but it's not working. What am I doing wrong? How can the code be updated so the desired result is achieved?
<script type="text/javascript">
const old_url = "https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=14";
const searchParams = new URLSearchParams(old_url);
const ID = searchParams.get("ID");
const new_url = `https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=${ID}&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO`;
console.log(new_url);
</script>
<html>
This is a link
This is a link
This is a link
This is a link
</html>
did you try clearing the Cache, if not try clearing it? hopefully, it should work,
Regards
The following may work for what you are trying to achieve here:
const old_url = "https://example.com/_layouts/15/listform.aspx?PageType=6&ListId=%7B6DDF7ABCX%2D5A27%2D4BEB%2DB4F9%2D158FAA3F0B34%7D&ID=14";
const searchParams = new URLSearchParams(new URL(old_url).search);
const ID = searchParams.get("ID");
const new_url = `https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=${ID}&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO`;
// Another way to do this
const new_url_alt = new URL('https://example.com/Lists/Your%20Col/Item/editifs.aspx?ID=${ID}&Source=https://example.com/Lists/Your%20Col/AO12.aspx&DefaultView=AO');
search_params_new.set('ID', ID);
new_url_alt.search = search_params_new;
console.log(new_url);
console.log(new_url_alt); // Same result
document.querySelectorAll(`a[href="${old_url}"]`).forEach(elem => elem.href = new_url); // Or new_url_alt; Both shall work

How change the content of last index in array?

I have one address and want to change some element,My address in bellow :
var address = "http://20.0.1.8/x-manufacturer/senders/d7aa5a30-681d-4e72-92fb-f0ba0f6f4c3e/sample-data";
I want to change the content of last index of var address "sample=data" to "new-data",I wrote the bellow code for solve it but didn't give me what I need!
let array_address = address.split('/');
var new address = array_address.splice(0,9,"new-data");//It just remove last index,didn't replace.
I assume you do not know what the last bit of the address is
let url = new URL("http://20.0.1.8/x-manufacturer/senders/d7aa5a30-681d-4e72-92fb-f0ba0f6f4c3e/sample-data")
let path = url.pathname.split("/")
path[path.length-1] = "new-data"
url.pathname=path.join("/")
console.log(url.href)

Retrieve the hyperlink on a specific text string within Google Doc using Apps Script

I'm trying to use Google Apps Script to get the hyperlink from a specific string found in this Google Doc.
The string is ||stock||
The hyperlink is https://www.cnbc.com/quotes/?symbol=aapl&qsearchterm=aapl
Any help is greatly appreciated.
The code I'm currently using
function docReport() {
var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1XNiqgJ_hM2SWjoR-OTsq1w-ZFKvTIERDIs_NOWJpckY/edit');
var body = doc.getBody();
Logger.log(body.getParagraphs().length);//get the number of paragraphs
//https://www.udemy.com/apps-script-course/learn/v4/t/lecture/10208226?start=0
for (var x=0;x<body.getParagraphs();X++) {
var el = body.getChild(x);
Logger.log(el.getText());
}
var bodyText = body.getText();
var words = bodyText.match(/\S+/g); // get word count for body - https://stackoverflow.com/questions/33338667/function-for-word-count-in-google-docs-apps-script
Logger.log(words.length); // retruns # of words
var paragraphAll = body.getParagraphs(); // gets all paragraph objects in a document
Logger.log(paragraphAll);
var paragraphText = paragraphAll[1].getText().match(/\S+/g);
Logger.log(paragraphText.length); // retruns # of words in a paragraph
}
You want to retrieve hyperlink of the text of ||stock||.
If my understanding is correct, for example, how about this sample script? In your situation, the text value which has a link has already been known. The sample script uses this situation.
By the way, from your question, I'm not sure whether there are several values of ||stock|| in the document. So this sample script supposes that there are several values of ||stock|| in the document.
I think that there are several answers for your situation. So please think of this as one of them.
Sample script:
var searchValue = "\\|\\|stock\\|\\|"; // Search value
var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1XNiqgJ_hM2SWjoR-OTsq1w-ZFKvTIERDIs_NOWJpckY/edit').getBody();
var searchedText = body.findText(searchValue);
var urls = [];
while (searchedText) {
var url = searchedText.getElement().asText().getLinkUrl(searchedText.getStartOffset());
urls.push(url);
searchedText = body.findText(searchValue, searchedText);
}
Logger.log(urls) // Results
Note:
If there is only one search value in the document, you can also use the following script.
var searchValue = "\\|\\|stock\\|\\|";
var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1XNiqgJ_hM2SWjoR-OTsq1w-ZFKvTIERDIs_NOWJpckY/edit').getBody();
var searchedText = body.findText(searchValue);
var url = searchedText.getElement().asText().getLinkUrl(searchedText.getStartOffset());
Logger.log(url)
References:
findText()
getLinkUrl()
If I misunderstand your question, please tell me. I would like to modify it.

ASP MVC JavaScript ActionLink multiple replace?

I want to build a Url.Action link and pass parameters and I found an example here on stackoverflow that shows how to replace the value:
var url = "#Url.Action("Export", "UserCalendar",new { from =
"_date", to="_to", groupId="_groupId" })".replace("_date",
_pdfExportStartDate);
How do I also replace _to and _groupId ? I tried
url = url.replace("_to",_pdfExportEndDate)
after the first replace call and although it makes the correct URL string the value (_to) is never passed to the controller.
You can simply add the querystring params to the base url (the one without any route values) as needed.
var _pdfExportStartDate = "11/11/2013";
var _toDate = "11/11/2013";
var baseUrl = "#Url.Action("Export", "UserCalendar")";
url = baseUrl +"?from = "+_pdfExportStartDate +"&to= "+ _toDate;

Categories

Resources