Replace a href with a js function call - javascript

I want to replace an url in a href with a call of a function that needs to include the url.
example:
I have the following string:
Google
some other text
Wikipedia
I want to get back a string like this:
Google
some other text
Wikipedia
I have tested some ways with RegEx, but I'm not good with RegEx. Does anyone have a solution for my problem?
EDIT:
Sorry, I forgot to write. I'm building an appcelator application. I can't use jQuery or "document". I think the only way is a RegEx.

Give this regex a try:
/href="([^"]+)/g
Here is a sample of its usage (JsFiddle Demo)
var subject = 'Googlesome other textWikipedia';
var result = subject.replace(/href="([^"]+)/g, 'href="javascript:anyFunction(\'$1\')');

If you give your hrefs unique IDs you can do this:
var val = $("#myHref").attr("href");
$("#myHref").attr("href", "javascript:anyFunction('"+val+"');");
If you want to avoid unique IDs then you can do this (applied to all a's):
​$("a").each(function() {
var val = $(this).attr("href");
$(this).attr("href", "javascript:anyFunction('"+val+"');");
});​​​
If you want to avoid applying this to all hrefs you can give all the hrefs you want changed a class then use a selector like this: $(".hrefToModify")...

NEW:
If you can use javascript, then can you get access to the anchor tag itself? if so:
anchor_element.href = "javascript:anyFunction('" + anchor_element.href + "')";
OLD:
<a id="link1" href="www.google.com">Google</a>
some other text
<a id="link2" href="www.wikipedia.org">Wikipedia</a>
<script>
document.getElementById('link1').addEventListener('click', function(e) {
alert('hello');
e.preventDefault();
return false;
});
</script>

Related

How to get the href src value from a string

A string contains entire value of a html.i need to get the value of href tag i.e. src value.please help me to solve.
var alltext="a href="images/BGL30NA-10.JPG" target="""
var str=allText;
'a href="images/BGL30NA-10.JPG" target=""'.match(/href="(.*?)"/)[1]
try this regex .
if you using jQuery:
try this:
var href = $('a').attr('href')
but better if you have <a></a> with something id and then
var href = $('#youId').attr('href')
hope this may help you.
try this, it will gives the value of href in javascript, below work only if you assign id attribute in your anchor tag <a href="images\images1.jpg" id="image1">
for only value of href
document.getElementById("image1").getAttribute("href"); here is Jsfiddle
if you want to get full path then use this:
for full path of href document.getElementById("aaa").href; here is Jsfiddle
if you have any doubts, ask it in below comment. #sriram
Parse the string before and use appropriate DOM functions:
str = "hello, <b>my name is</b> jQuery.";
html = $.parseHTML( str );
# use $('a').attr('href') or any other selector here
The mandatory link to TONY THE PONY.

Insert current URL into a link using JS and HTML

So, Ive read through similar things but I still can't find an answer that applies more closely to what I'm doing. I am attempting to use JS to get the current page URL and append it to a social media sharing link like this:
<a href="http://reddit.com/submit?url=CURRENTPAGE.html; title="This is a post!" target="_blank">
Using Javascript, I've managed to assign the current URL to a variable:
<script>
var x = window.location.href;
document.getElementById("smsharing").innerHTML = x;
</script></p>
And I made sure it worked by doing a test display of it. So what exactly is the proper method/syntax for actually putting 'x' in place of CURRENTPAGE.html???
I know this is a STUPID question, but I'm really stumped. Specifics help, because part of the problem is that I have precious little knowledge of JS. Thoughts?
This should do it:
<script>
baseurl="http://www.facebook.com?"
function buildURL(item)
{
item.href=baseurl+window.location.href;
return true;
}
</script>
</head>
<body>
<a onclick="return buildURL(this)" href="">Google</a>
</body>
Get the elements current href which doesn't have the url value and append the current url.
Modified HTML
<a id='smsharing'
href="http://reddit.com/submit?url="
title="This is a post!"
target="_blank">link</a>
Script
<script>
var x = window.location.href;
var link = document.getElementById("smsharing"); // store the element
var curHref = link.getAttribute('href'); // get its current href value
link.setAttribute('href', curHref + x);
</script>
Using just pure JavaScript you can set the href of the link by just having the base href as a string and then add the variable where ever it is needed.
var x = window.location.href;
document.getElementById("linkid").href = "http://reddit.com/submit?url="+encodeURIComponent(x);
Using jQuery it is as simple as:
$('a').attr("href",x);
You should simply replace innerHTML by href :
document.getElementById("smsharing").href = x;
Hope this helps.
Once you have access to the current URL, you then want to find the element and replace CURRENTPAGE.html. To do so, you'll need some way to select the element. Let's give it an ID:
<a id="myLink" href="http://reddit.com/submit?url=CURRENTPAGE.html"></a>
Now we can grab the link like so:
var link = document.getElement('myLink');
Let's get the URL again, and give it a better variable name:
var url = window.location.href;
Now let's update the HREF attribute of link:
link.href = link.href.replace('CURRENTPAGE.html', url);
And that's it!
Create another variable for the complete href attribute of your link:
var myURL = "http://reddit.com/submit?url=" + x;
Then replace the current href attribute with that variable:
docment.getElementById("YourLinkTagID").href = myURL

Split value of a html tag

I would like to split some content from an "a" html tag. I was starting over with jquery. My code is like this but it is not working:
$("a.uribb").each(function() {
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).append(+id+);
});
​
And the HTML tag is this:
<a href="http://dereferer.org/?http://example.com/" target="_blank" class="uribb">
http://example.com/
</a>
I wanted to split out the http://dereferer.org/? part and leave the other there. How could I do this?
Try to use .text() instead of .append() if you want to replace the content. Also, there is no need for the + before and after the id.
You could try this instead:
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).text(id);
Update
Reading through the question again, I'm not sure if you want to replace the content of the a-tag or the the value of the href. In case of the latter, try this:
var id = $(this).attr("href").replace("http://dereferer.org/?", "");
$(this).attr("href", id);
Notice
Since jQuery 1.6, it is preferred to use .prop() instead of .attr().
How about that?
$("a.uribb").attr("href", function(i, val) {
return val.substring(val.indexOf("?") + 1);
});​
DEMO: http://jsfiddle.net/zQdL4/
It's interesting but for your markup the following code should also work :)
$("a.uribb").attr("href", function() {
return $.trim(this.innerHTML);
});​
Right, so what you want is this.
<a href="http://example.com/">...
Try this.
$("a.uribb").each(function() {
var indirect_url = $(this).prop("href");
var direct_url = indirect_url.replace("http://dereferer.org/?", "")
$(this).prop('href', direct_url);
});
You could of course do this in fewer lines, but this way it's clear what's going on. Specifically, replace() does not modify the string it operates on.

Get a value from an attribute and add it as another attribute?

How can I use jQuery to get a string of text from the onclick attribute and set it as the href attribute.
Here's the fiddle I'm working with: http://jsfiddle.net/MBmt5/
I want to take only TrackPackage.asp?track=95213&ship=OTHER&ShippingMethod=3 from the onclick attribute and prop it to an href attribute
So that it would end up looking like this: http://jsfiddle.net/52Nha/
Unfortunately, I have no idea how to accomplish this. Can anybody help me? Must be compatible with jQuery 1.4.2. Thanks.
Update
Of course I'd begin with:
$(document).ready(function(){
$('span.trackpackagebutton').closest('a').removeAttr('href');
});
​
Ugly but I hope this will help you.
$('a').attr('href',
$('a')[0].getAttribute('onclick')
.replace("window.open('", '').split(',')[0].replace("'", ''))
.removeAttr('onclick');​​​​​​​​​​​​​​​
Working demo - http://jsfiddle.net/MBmt5/5/
Note: Based on your markup structure you can use the right selector and reuse the above code.
E.g: The below code will execute this logic for all the anchors on the page which have onclick attribute which has window.open.
$('a[onclick^="window.open"]').each(function(){
$(this).attr('href',
this.getAttribute('onclick')
.replace("window.open('", '').split(',')[0].replace("'", ''))
.removeAttr('onclick');​​​​​​​​​​​​​​​
});
Here's one way:
http://jsfiddle.net/MBmt5/2/
http://jsfiddle.net/GaZGv/1
var $a = $('span.trackpackagebutton').closest('a');
var href = $a.attr('onclick').split('(')[1].split(',')[0].replace(/'/g, '');
$a.attr('href', href).removeAttr('onclick');
alert(href)​

Remove anchor, but not arguments, via JavaScript

I want to change the following example URL
http://www.mydomain.net/site?argument1=test1&argument2=test2#anchor
to
http://www.mydomain.net/site?argument1=test1&argument2=test2
with JavaScript. How would I best do that?
EDIT: With 'anchor' and the other text elements, I meant generic elements. So the anchor could also be another text. Sorry.
If you're trying to change the current location's anchor, it's better to change window.location.hash:
window.location.hash = '';
In some browsers this will avoid a reload of the page as the URL changes.
Try this:
window.location = window.location.replace(/#anchor/,"");
OK, so I tried this, and it worked perfectly fine:
var url=window.location.toString();
url=url.replace(/#anchor/,'');
window.location=url;
This should replace #anchor but also #anchor_etc or #anchor-etc from your url
var url = "http://www.mydomain.net/site?argument1=test1&argument2=test2#anchor";
url = url.replace(/\#[a-z\-\_]+/i, '');
window.location = window.location.replace('#anchor','');

Categories