pulling text from url and putting text back in url with javascript - javascript

I have tried googling this but can't find what I'm looking for. I have a url that has a number in it. I want to be able to take the number that is there and depending on what number is there then interject a name back into the url. For example:
Let's say the url is: www.example.com/video15637
Can I take that number and then do something like:
var nameVariable;
if(video15637){
nameVariable = video15637;
}
if(video26597){
nameVariable = video26597;
}
if(video18737){
nameVariable = video18737;
}
then, somehow interject the namevariable back into the url that is displayed?

You can try with:
var a = document.createElement('a');
a.href = 'http://www.example.com/video15637';
var nameVariable = a.pathname.substr(1); // video15637

You can simple use .split() or combination of .substr() and .lastIndexOf()
var url = 'www.example.com/video15637';
var video = url.split('/')[1];
alert(video)
OR
var url2 = 'http://www.example.com/video15637';
var video2 = url.substr(url.lastIndexOf('/') + 1);
alert(video2)
Combined DEMO

Related

Way to get full param value from an URL

I am try to get the data from the param in the URL
http://localhost:8080?test=1&redirectURL=http://localhost:8082/#/abc?param=1
I did
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const redirectURL = urlParams.get('redirectURL'); // result: http://localhost:8082
but currently, the URL contain the hash code inside URL so the value return just http://localhost:8082
Is there any way to get full url http://localhost:8082/#/abc?param=1 by getting the param redirectURL
Thank you very much
I hope the following is useful for you.
var url_string = window.location.href;
var url = new URL(url_string);
var paramsTest = url.searchParams.get("test");
var paramsRedirectURL = url.searchParams.get("redirectURL");
console.log(paramsRedirectURL)
console.log(paramsTest)
Example here: https://codepen.io/yasgo/pen/dypWKoM
Maybe this can work for you
var afterHash = window.location.hash;
var beforeHash = window.location.href;
var fullURL = beforeHash ;
if(afterHash != '') // if there is something after hash and hash is exists in url then add the afterHash value in full url
{
var fullURL = beforeHash +"#"+ afterHash ;
}
console.log(fullURL);
I think the biggest issue here is that your redirectURL is not encoded. It should be encoded before it ends up in the URL, because otherwise the params and hashes from the nested URL are going to spill into the parent URL.
I obviously don't know if it would make sense for your project, but I think I would use domurl.
Maybe you should just use encodeURIComponent and possibly decodeURIComponent later, but I wanted to point out that domurl handles encoding and decoding automatically. Just as an example:
var url = new Url("http://localhost:8080?test=1");
url.query.redirectURL = 'http://localhost:8082/#/abc?param=1';
console.log( url.toString() );
// http://localhost:8080/?test=1&redirectURL=http%3A%2F%2Flocalhost%3A8082%2F%23%2Fabc%3Fparam%3D1
So again, what the encoded URL does is it prevents params from spilling from the nested URL to the parent URL and enables you to read redirectURL as a single string that you can then parse again to see/edit whatever params it has. The other important point is that I'm removing the hashtag with replace('/#/','/') in order to read the params from redirectURL:
Here's a slimmer jsfiddle where I'm just extracting the param and leave everything else out.
You'll definitely want to check dev tools consode log instead of the one stackoverflow offers, to make any sense of the objects.
console.log('');
// I'm encoding the redirectURL here, but in the real world it should be encoded before it's added as a parameter.
var url = new Url("http://localhost:8080?test=1&redirectURL="+ encodeURIComponent("http://localhost:8082/#/abc?param=1"));
console.log('url', url);
// So now that I've separated `url.query.redirectURL`, I can read that URL and its params separately...
var redirectUrl = new Url( url.query.redirectURL.replace('/#/', '/') ); // The hashtag is removed
console.log('redirectUrl:', redirectUrl );
console.log('redirectUrl - (param):', redirectUrl.query.param );
console.log('redirectUrl - path:', redirectUrl.path );
// If you need to use redirectURL without modifications you can just take the url param as is:
console.log( 'redirectUrl - no edits:', url.query.redirectURL );
// If you need to edit the params, you could do that and put just back the hashtag
redirectUrl.query.param = 'changed the param';
redirectUrl.path = '/#' + redirectUrl.path
console.log('redirectUrl - edited:', redirectUrl.toString() );
<script src="https://cdn.jsdelivr.net/npm/domurl#2.3.4/url.min.js"></script>

How do I get rid of everything, every string before a specified word in jquery?

I'm trying to do a simple string replace in jquery but it seems to be more than just a simple code.
In mygallery have this image link (note the 2x ../)
var imgName= '../../appscripts/imgs/pic_library/burn.jpg';
In browsegallery I have something like this:
var imgName ='../../../../../appscripts/imgs/pic_library/burn.jpg';
and sometimes depending on where do I get the image source from, it can be like this
var imgName = '../appscripts/imgs/pic_library/burn.jpg';
What I'm trying to do is, to get rid of all of those '../', and to gain the imgName like this:
'appscripts/imgs/pic_library/burn.jpg';
So this way I can get the right directory for my mobile app.
Can anyone help me on how to get rid of all those (without even counting) '../'?
Best Regards!
Using the replace method of a string you can remove all cases of the
../
var imgPath = '../../../../../appscripts/imgs/pic_library/burn.jpg';
var imgName = imgPath.replace(/\.\.\//g, '');
console.log(imgName);
Here is a direct answer to your question that does not tie you to the "/appscripts" in your example:
const imgName= '../../appscripts/imgs/pic_library/burn.jpg';
const img = imgName.split('../')
.filter((val) => val !== '')
.join('');
If the desired end path is always the same - just get the unique part (the actual file name) and add it to a string of the path you require. the following usies lastIndexOf to get the actual file name from the relative path and then builds a string to give the desired path plus the file name.
var fileSource = 'appscripts/imgs/pic_library/burn.jpg';
let lastIndex = fileSource.lastIndexOf('/');
let fileName = fileSource.slice(lastIndex + 1, fileSource.length); // gives burn.jpg
let imageSource = 'appscripts/imgs/pic_library/' + fileName;
console.log(imageSource); // gives appscripts/imgs/pic_library/burn.jpg
Thank you all for helping me out.
I finally solved this using imgName.split('/appscripts/');
Like this:
var replaceImg = image.split('/appscripts/');
var finalImageName = "../../../appscripts/"+replaceImg[1];
Thank you again!
You can create a jQuery plugin, i.e: $(...).imagify()
Use a regex to replace that pattern: .replace(/(\.){1,2}\//g, '')
$.fn.imagify = function() {
var src = this.attr('src') || '';
this.attr('src', src.replace(/(\.){1,2}\//g, ''));
};
$('img').imagify();
$('img').each((_, obj) => console.log($(obj).attr('src')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='../../../../../appscripts/imgs/pic_library/burn.jpg'>
<img src='../appscripts/imgs/pic_library/burn.jpg'>
<img src='./../../appscripts/imgs/pic_library/burn.jpg'>
Resource
How to Create a Basic Plugin

javascript: get hex from long url

For example i have such urls:
https://portalvhdsk7w6i7k9.blob.core.windows.net:443/project/5633cc12da73d9160c4cf146.dat
https://portalvhdsk7w6i7k9.blob.core.windows.com/project/5633cc12da73d9160c4cf146.dat
https://example.com/project/5633cc12da73d9160c4cf146.dat
can i somehow get only 5633cc12da73d9160c4cf146 using only js? is it possible?
You can split the string by / and the pop() the final element. Try this:
var url = 'https://portalvhdsk7w6i7k9.blob.core.windows.net:443/project/5633cc12da73d9160c4cf146.dat'
var hex = url.split('/').pop().replace('.dat', ''); // = '5633cc12da73d9160c4cf146'
If you want to get the location of the current page, use document.location.
Check this:
var url = "https://portalvhdsk7w6i7k9.blob.core.windows.net:443/project/5633cc12da73d9160c4cf146.dat"
var indexofProd = url.indexOf("project/");
indexofProd = indexofProd + 8;
var indexofdotDat = url.indexOf(".dat");
var number = url.substring(indexofProd,indexofdotDat);
alert(number);

How to get a specific portion of the url using javascript?

var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()

Removing parameter values of a url in the next page using javascript only

I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}

Categories