Javascript, change middle part of a link - javascript

I have a list of items that are links, and I want to only a part of the link to change based on a input field.
For example:
http://www.myexamplepage.com/?q=%22ITEM1%22&sort=date&from=2017-01-11&to=2017-01-20
So if I want to do this:
<form><input id="date"><input></form>
<a href="http://www.myexamplepage.com/?q=%22ITEM1%22&sort=date&from=XXXXXX&to=XXXXXX">
<a href="http://www.myexamplepage.com/?q=%22ITEM2%22&sort=date&from=XXXXXX&to=XXXXXX">
<a href="http://www.myexamplepage.com/?q=%22ITEM3%22&sort=date&from=XXXXXX&to=XXXXXX">
Where XXXXXX changes depending on the value i input in the input field. Because another part of the link changes (ITEM1, ITEM2, ITEM3 etc.) this solution for example, will not work: How to change part of HTML href elements with javascript all solutions I find are like this one, or they completely changes everything after XXXXXX in the link.
Any tips?

You can cut out the part of the url string using indexOf and subString.
Fiddle example: https://jsfiddle.net/xdckhvyp/
var string = 'http://www.myexamplepage.com/?q=%22ITEM3%22&sort=date&from=XXXXXX&to=2017-01-20';
var startingPoint = string.indexOf('from=') + 5;
var endingPoint = string.indexOf('&to');
string.substring(startingPoint, endingPoint);

Related

Why will the colour of the active link not highlight blue? [duplicate]

I have an anchor tag that has a local href value, and a JavaScript function that uses the href value but directs it to a slightly different place than it would normally go. The tag looks like
<a onclick="return follow(this);" href="sec/IF00.html"></a>
and a JavaScript function that looks like
baseURL = 'http://www.someotherdomain.com/';
function follow(item) {
location.href = baseURL + item.href;
}
I would expect that item.href would just return a short string of "sec/IF00.html", but instead it returns the full href, "http://www.thecurrentdomain.com/sec/IF00.html". Is there a way that I can pull out just the short href as put in the anchor <a> tag? Or do I lose that by natural HTML behavior?
I suppose I could use a string manipulation to do this, but it gets tricky because my local page may actually be "http://www.thecurrentdomain.com/somedir/somepath/sec/IF00.html", and my href field may or may not have a subdirectory in it (for ex href="page.html" vs. href="sub/page.html"), so I cannot always just remove every thing before the last slash.
You may wonder why I am requesting this, and it is because it will just make the page a lot cleaner. If it is not possible to get just the short href (as put in the anchor <a> tag), then I could probably just insert an extra field into the tag, like link="sec/IF00.html", but again, that would be a little messier.
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
document.getElementById("link").getAttribute("href");
If you have more than one <a> tag, for example:
<ul>
<li>
</li>
<li>
</li>
<li>
</li>
</ul>
You can do it like this: document.getElementById("link")[0].getAttribute("href"); to access the first array of <a> tags, or depends on the condition you make.
This code works for me to get all links of the document
var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.
$(".test a").on('click', function(e) {
console.log(e.target.href); // logs https://www.test.com/#test
console.log(e.target.hash); // logs #test
});
The href property sets or returns the value of the href attribute of a link.
var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
var url="https://www.google.com/";
console.log( url+hello);
document.getElementById("aaa").href; //for example: http://example.com/sec/IF00.html

Dynamically setting href tag

On my page there're 2 href links like this:
Name
Phone
The URL that the user is on is based on this format:
http://localhost/site/name/ASDF
I want it so that the website automatically fill out the href boxes like this
Name
Phone
I know I can just assign an id to each of the a tag, and have javascript set the href, but I was wondering if there's a way to do it without having to have a function that sets it once the page is loaded.
Is there a way to do it like I want to? The main problem is the ASDF which is a unique string that the user can specify, so on the page with URL:
http://localhost/site/name/John
the 2 href will be:
Name
Phone
You should get current url then split it and get dynamic name then insert it to href tags. see this exaple:
var fakeUrl = $('#fakeURL').text();
var split = fakeUrl.split('/');
var user = split.pop();
$('#name').attr('href','/site/name/'+user);
$('#phone').attr('href','/site/phone/'+user);
#fakeURL {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="name" href="#">Name</a>
<a id="phone" href="#">Phone</a>
<span id="fakeURL">http://localhost/site/name/ASDF</span>
or another user:
var fakeUrl = $('#fakeURL').text();
var split = fakeUrl.split('/');
var user = split.pop();
$('#name').attr('href','/site/name/'+user);
$('#phone').attr('href','/site/phone/'+user);
#fakeURL {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="name" href="#">Name</a>
<a id="phone" href="#">Phone</a>
<span id="fakeURL">http://localhost/site/name/Jiff</span>
it's an example and will read from fake url you should use this code in your server to get real url:
var url = window.location.href;
var split = url.split('/');
var user = split.pop();
$('#name').attr('href','/site/name/'+user);
$('#phone').attr('href','/site/phone/'+user);
jsFiddle
If your server-side is generating the 's dynamically, you can make it without problem.
If your links are static you need javascript because parts of your href is based on their own properties.
If you use jquery, you dont need to add ids in links in order to fill hrefs, but, If your document is big, the script should be very inefficient.
If you give me more info about your use case, i can help you better.
you can try this..
use query string like localhost/site?name=Max
then do this
$url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].DIRECTORY_SEPARATOR.$_GET['name']

Convert raw html to text with javascript and regex

I have raw html with link tags and the goal I want to achieve is extract href attribute from tags and all text between tags except tags.
For example:
<br>#EXTINF:-1 tvg-name="1377",Страшное HD<br>
<a title="Ссылка" rel="nofollow" href="http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C01_STRASHNOEHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2" target="_blank">http://46.61.226.18/hl…variant.m3u8?version=2</a>
<br>#EXTINF:-1 tvg-name="983" ,Первый канал HD<br>
<a title="Ссылка" rel="nofollow" href="http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C06_1TVHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2" target="_blank">http://46.61.226.18/hl…variant.m3u8?version=2</a>
have to convert to:
#EXTINF:-1 tvg-name="1377",Страшное HD
http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C01_STRASHNOEHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2
#EXTINF:-1 tvg-name="983" ,Первый канал HD
http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C06_1TVHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2
I tried different regex's:
Here what I did
var source_text = $("#source").val();
var delete_start_of_link_tag = source_text.replace(/<a(.+?)href="/gi, "");
delete beginning of the tag to the href attribute
var delete_tags = delete_start_of_link_tag.replace(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gi, "");
delete all tags </a>, <br>
example
And then I want to delete all text after href values to the end of the line.
What regex should i use in replace method or maybe where is a some different way to do this converting?
Formatting Anchor Tags
In your example , you are not replacing the "> part form the html.
So check this example
use this code to remove everything after href close quote(' or ")
var delete_tags = delete_start_of_link_tag.replace(/".*/gi, "");
And few things to notice are
1.The value in href is enclosed in single quote(') or double quotes("), both are valid.
2.The exact regex to match all href in a given string or content is href=[\"|'].*?[\"|']
3.Some patterns in href values , I came across are below.
http://www.so.com
https://www.so.com
www.so.com
//so.com
/socom.html
javascript*
mailto*
tel*
So if you want to format URL's then you have consider the above cases and i may have missed some.
Looks like you're already using jQuery.
Get the href of each anchor
$('a').each(function(){
var href = $(this).attr('href');
});
Get the text of each anchor:
$('a').each(function(){
var text = $(this).text();
});
You haven't shown a wrapper element around these but you can get the text (without tags) of any selection.
var text = $('#some_id').text();
Example

Split website link into 2 href link?

On my website public: http://abv.mk/company.aspx?id=40056 , i want to split http://www.donholding.com.mk & http://www.webklinika.mk to be separate links (and separate clickable like two different links - hrefs).
But in my admin-panel for the field website i only have 1 field available, where i input 2 web site links splited with ","
So is it possible in the public asp-file "company.aspx", to edit the file and insert some Javascript code, so i split the link from 1 href to 2 hrefs ?
<span id="ctl00_ContentPlaceHolder1_lblComWeb"><a target="_blank" href="http://www.donholding.com.mk, www.webklinika.mk" title="">www.donholding.com.mk, www.webklinika.mk</a> | donholding#live.com</span>
I'm guessing you have one field in the DB which stores the URL. This should probably instead be its own table - company_url, which takes company_id (in thie case, 40056) and the URL. You should bring back a DataSet, and create a HTML string to put in to the Literal (or whatever you're using).
That's the "you should do this" answer.
Now.. you could do...
$(document).ready(function(){
var el = $('span[id$="lblComWeb"]');
var el_a = el.children('a');
links = el_a.html();
links = links.split(',');
el.html('');
$.each(links,function(l){
var e = ''+links[l]+'';
el.append((l > 0 ? ',' : '') + e);
});
});
as you're already using jQuery. However, it's cheap and dirty and nasty and yucky.
Just putting that snippet in to your company.aspx file (between some tags) should do the trick.
This page only allows you to display one website.
The href property of the a html tag only support reference to one address/page.
What you could do is put there the link to another page which is yours, and in this page you can put as many different links to anywhere you want and other information too. Maybe search for some URL shortener service which allows something like this.
Now, if you actually do have access to the source code and modify it, all you have to do is:
<span id="ctl00_ContentPlaceHolder1_lblComWeb">
<a target="_blank" href="http://www.donholding.com.mk" >www.donholding.com.mk</a>, <a target="_blank" href="www.webklinika.mk" >www.webklinika.mk</a> | donholding#live.com
</span>

How do I give an ID to part of the contents of a <title> tag?

I have a title tag that looks something like this:
<title>My Page Title - Photo #3</title>
I want to use JavaScript to change the numeric part of it, without having to hard code the "My Page Title - Photo #" string which is generated server side.
I tried wrapping the number in a span so that I could change the contents of the span:
<title>My Page Title - Photo #<span class="photoid">3</span></title>
But it seems HTML is not allowed in the title tag. I'd really like to pursue the class approach if possible as that would allow me to use a line of jquery such as this:
$('.photoid').html(new_photoid);
Did I mention that the photoid appears in several places on the page, which is why I want to be able to use this oneliner to change them all at the same time? For example:
<p>A paragraph also containing the number <span class="photoid">3</span></p>
A title can only have text, so you need to parse it out.
document.title = document.title.replace(/\d+$/, "new value");
title can't be set like that,
it's not a child of .html
some thing like
var num = 3;
document.title = "foo "+num
to set the title, then reuse num for these photoids.
Use the jQuery onDocumentReady syntax:
$(function () {
var elements = $('.contains_photoid');
elements.html(elements.html().replace("3", "4"));
$(document).attr('title', $(document).attr('title').replace("3", "4"));
});
You can't see the title change in this example, but that is the syntax. See Changing the page title with Jquery
The "3" and "4" can be changed to anything, so you can create the page with a unique character string in place of the real ID in order to easily replace it if it appears in text with numbers already in it.
http://jsfiddle.net/ZmXj5/1/
Javascript
var photoID = 355; //this assumes you have some code where you set this photoID value
var title = document.title;
title = title.substr(0,title.lastIndexOf('#')+1);
document.title = title+photoID;
See this fiddle for proof: http://jsfiddle.net/xrkhA/
(I used a div content because you can't use title in jsfiddle)
You can either use, but $('title') will fail in IE8
document.title="new title";
or
$('title').html('new title');
or
$(document).attr('title','new title');

Categories