Remove everything before the URL text - javascript

I have this you URL passby my variable and somehow I get the URL differently, so I have to remove it.
My URL
http://localhost/Air.com/Img/team/12345/12345.png
I am using this code to remove it
Image_src = url
// Image_src = Image_src.replace(/https?:\/\/[^\/]+\/+/i, "");
But somehow sometimes I have other URL, is there any way I can remove everything before /Img
Img/team/12345/12345.png
No matter what URL in front, remove everything before Img.

Try this:
var Image_src = url.substring(url.indexOf("/Img/"));
If you don't want the / character also just add 1, like so:
var Image_src = url.substring(url.indexOf("/Img/") + 1);

This may help you.
var parser = document.createElement('a');
parser.href = "http://localhost/Air.com/Img/team/12345/12345.png";
parser.pathname.substring(parser.pathname.indexOf('/',2)) // return /Img/team/12345/12345.png

Related

Appending current URL parameters onto anchor link

At a page like
https://www.example.com/?firstname=Steven&lastname=Smith&email=steve%40gmail.com&phone=0404555555
I have a button (anchor link) #ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell that links to https://www.example.com/form
I'd like to append the URL parameters from the current URL to the button's URL, so that the button's href is now https://www.example.com/form/?firstname=Steven&lastname=Doig&email=steve%40gmail.com&phone=0404555555
How can I do this with JavaScript please?
Use window.location.search:
var url = "https://exmaple.com";
var newurl = url + window.location.search;
newurl will contain all the get (ex. ?something=something&something2=something5) data.
To change the href of a:
var button = document.getElementById('#ptsBlock_553944');
button.href = button.href + window.location.search;
If you don't care about supporting older browsers you can use the URL API and URLSearchParams.
function appendCurrentUrlSearchParams(anchorElement) {
const currUrlSearchParams = new URL(window.location.href).searchParams;
const link = new URL(anchorElement.href);
// uncomment this line if you want to clear query parameters already present in the anchor url
// link.search = '';
for (const entry of currUrlSearchParams.entries()) {
link.searchParams.append(entry[ 0 ], entry[ 1 ]);
}
anchorElement.href = link.href;
}
Usage in your case:
appendCurrentUrlSearchParams(document.querySelector('#ptsBlock_553944 .ptsCell:nth-of-type(1) .ptsEditArea.ptsInputShell'));
Read Html select using select to change the link of a button with Javascript
specifically the section on
Get the element with something like document.getElement MDN getElement Link
Change the .href of that element to what you want.
function selectFunction() {
var x = document.getElementById("selectopt").value;
document.getElementById("mylink").innerHTML = x;
document.getElementById("mylink").href = "http://www." + x + ".com";
}
document.location.pathname = '/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510';
//get the document pathname I chose from document.location
let data = document.location.pathname;
let preUrlString = 'www.example.com/form';
let newString = preUrlString + data;
console.log(newString);
'www.example.com/form/questions/69240453/appending-
current-url-parameters-onto-anchor-link/69240510'
document.getElementById("mylink").href = newString;

Result of element is changing during getting it by script

I tried to get data with JavaScript:
The Text
var link = document.getElementById('link_Page')
var text=link.innerHTML;
var href=link.href;
I expect to see:
"/product/23" and "The Text "
But result is:
"http://localhost:60790/product/23" and "The Text "
Note: on jsfiddle.js I tested and result of text(not link) was fine. couldn't understand why it's gives me ' '
https://jsfiddle.net/mahma/ocwnufqb/
Note: on jsfiddle.js I tested and result of text(not link) was fine
.href will return the full URL of the linked resource, to get the exact value of the href attribute try using Element.getAttribute():
var link = document.getElementById('link_Page')
var text=link.innerHTML;
var href=link.getAttribute('href');
console.log(text);
console.log(href);
The Text
is the space character in HTML. You have a space character in the end of the a tag's text.
Here is the way you can do what you want.
var link = document.getElementById('link_Page')
var text = link.innerText;
var href = link.getAttribute('href');
console.log(text, href);
The Text

Downloading file made with jquery's .innerhtml breaks at the first "#"

I have this code:
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //displays fine
a.href = "data:image/svg+xml," + dd.innerHTML;
a.click();//downloaded file cuts off at the first "#"
}
When the alert displays it it's okay, the downloaded version is cut off before the first "#". How do I fix this?
Since this is part of a href, you need to url-encode your data first, eg.
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //should still display fine
a.href = "data:image/svg+xml," + encodeURIComponent(dd.innerHTML);
a.click();//should now not cut off.
}
The safe variation of # in a url is %23%0A (check out this tool: http://meyerweb.com/eric/tools/dencoder/).

How to split a string and then embed the second string (link) into the first string?

I'm fairly new to JavaScript and I have this RSS Feed I'm working with currently.
When I retrieve an item from the RSS feed, the following is displayed
Google Home Page http://www.google.com
How can I split this string, so that I can embed the second part of it (http://www.google.com) into the first part(Google Home Page)?
First - exclude the link by using following RegEx pattern (searches for string which starts with http://).
/http:\/\/.*[^\W+]/g
The matched value (Array) is being stored into url, now we are able to create the anchor element. (the value of href is the element 0 inside our matches array).
The link content is being generated by replacing the URL with empty space inside the retrievedResult. trim() is optional, I've used it just to remove remaining space.
retrievedResult.replace(url[0], "").trim()
Finally you can append the built anchor element.
var retrievedResult = "Google Home Page http://www.google.com";
var re = /http:\/\/.*[^\W+]/g;
var url = retrievedResult.match(re);
var anchor = '' + retrievedResult.replace(url[0], "").trim() + '';
$('body').append(anchor);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Okay, so this will be the string:
var string = "Google Home Page http://www.google.com";
Then we split it:
var split = string.split('http'); // ['Google Home Page ', '://www.google.com']
Then we create an a element:
var a = document.createElement('a');
Then we add the link as the href attribute of your anchor element:
a.href = 'http' + split[1];
And then we add the text as textContent of your anchor element:
a.textContent = split[0];
And finally we add the element to the body:
document.body.appendChild(a);
Here an example:
var string = "Google Home Page http://www.google.com";
var split = string.split('http');
var a = document.createElement('a');
a.href = 'http' + split[1];
a.textContent = split[0];
document.body.appendChild(a);
You can use jquery to get to your result
Working Example:
//This is HTML part
<div id="linkcontainer"></div>
<input id="str" value='Google Home Page http://www.google.com'>
<a id="createlink">CreateLink</a>
//This is js part
$('#createlink').click(function(){
createLink();
});
//function that makes link
function createLink(){
var str = $('#str').val();
var http = str.indexOf('http');
var url = str.substring(http);
var text = str.substring(0,http);
$('#linkcontainer').html(''+text+'');
}
Try this code on jsfiddle

Get relative URL from absolute URL

I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
I tried the following but it is not working:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));
A nice way to do this is to use the browser's native link-parsing capabilities, using an a element:
function getUrlParts(url) {
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
protocol: a.protocol,
hash: a.hash,
search: a.search
};
}
You can then access the pathname with getUrlParts(yourUrl).pathname.
The properties are the same as for the location object.
Below snippet returns the absolute URL of the page.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
If you need only the relative url just use below snippet
var myURL=window.location.pathname;
Checkout get relative URL using Javascript for more details and multiple ways to achieve the same functionality.
If by "relative URL" you mean the part of the string after the first single /, then it's simple:
document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));
This matches all the characters up to the first single / in the string and replaces them with the empty string.
In: http://localhost/my/page.jsp --> Out: /my/page.jsp
const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)
console.log(rel)
// Output: /path/#anchor?query=value
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#relativeto
var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"
URL.getRelativeURL
There's an public-domain extension for the standard URL object called getRelativeURL.
It's got a few cool tweaks like force reload, you should check it out!
Try it live.       View on Gist.
Example usage
//syntax: <URL to convert>.getRelativeURL(<relative to this URL>)
//link from Mypage to Google
a = new URL("https://google.com/search");
a.getRelativeURL("https://mypage.com")
== "//google.com/search";
//link from the current location.href
a.getRelativeURL();
//link from Olutsee to Polk
var from = new URL("http://usa.com/florida/baker/olutsee");
var to = new URL("http://usa.com/florida/polk");
to.getRelativeURL(from) == "../../polk";
don't forget that \ is an escape character in strings, so if you would like to write regex in strings, ensure you type \ twice for every \ you need. Example: /\w/ → "\\w"
Below you can find script on that here we have only one problem which is one manual work, we want to add split attribute ie, if your site link is: Get relative URL from absolute URL
we want to url as below:
/questions/6263454/get-relative-url-from-absolute-url
so in below code we have to add .com instead of .net ie,
var res = at.split(".net"); here we want to add as per our requirement now i need to seperate after .com so code will be "var res = at.split(".com");".
i think you guys got that point if you have still doubt let me know please
and to see changes in code by inspecting:
$(document).ready(function(){
$("a").each(function(){
var at= $(this).attr("href");
var res = at.split(".net");
var res1 = res[0];
var res2 = res[1];
alert(res2);
$(this).attr("href",res2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>

Categories