Regex pattern to replace and disable href links - javascript

I need to disable a link tags (whose href attribute value starts with log.html) in my html table. I am trying to use string replace to do.
The code line looks approximately like this, str.replace(/log.html...../g,'') where there must be a regex pattern in the place of dots.
All patterns like this,
<a class="log" href="log.html#s1-s1-s1"></a>
<a class="log" href="log.html#s1-s2-s100"></a>
<a class="log" href="log.html#s10-s5-s1"></a>
must be made as,
<a class="log" href="#"></a>

You can use the following to match:
/log.html#[^"]*/g
And replace with #
Code:
str.replace(/log.html#[^"]*/g,'#')
See DEMO

What you are looking for is string.match(). This function returns an array of the match and any captured groups. You could test all your links with something like this:
$('a').each(function() {
href = $(this).attr("href");
if(href.match(/^log\.html/)) {
$(this).attr("href", "#");
}
});
Fiddle

This regex pattern seems to work given that the url is accessable as a string. This can easily be accomplished with jQuery.
str.replace(/log\.html.*/g,'#')

Since href and ".." are always available in a link, i would use a simple
/href=".+"/g
DEMO

Related

Edit a href tag url before it's clicked on?

I have a url that looks something like this:
https://url.com/a b c
which is as expected. When the user clicks on this however, it redirects to the wrong link because the link actually has underscores instead of spaces in its url. is there any way to edit this url so that right before the url is clicked, the spaces turn into underscores? The url would look like so:
https://url.com/a_b_c when the user clicks it instead of what was above. Below is my attempt:
<a target="_blank" style="font-size: 9px" href="https://url.com/{{label}}">[Details]</a>
where label is equal to a b c. I tried the following:
<a target="_blank" style="font-size: 9px" href="https://url.com/{{label.replace(" ", "_")}}">[Details]</a>
so that a b c would turn into a_b_c but that didn't seem to work because the curly braces can't actually execute the replace function. Any help would be appreciated. If possible, I would also want to append some text to the end of this newly replaced label so it would look like: a_b_c_new_text Thanks!
For some reason I was having difficulty getting the global regular expression replace .replace(/ /g, '_') working within the curly braces. Instead, I opted for a solution from this SO answer.
<a ng-href="http://url.com/{{label.split(' ').join('_')}}">Click Me</a>
Here's the Codepen.
Keep in mind that ng-href is better than href because it will not throw a 404 before the curly braces are evaluated.
Try this: JS Fiddle
var $link = document.getElementById('test'),
$href = test.href;
test.addEventListener('mouseover', function(){
$href = $href.replace(/%20/g, '_');
console.log($href);
this.href = $href;
});
<a id="test" href="https://url.com/a b c">Link Data</a>

remove specific href children jquery

My code looks something like that:
<a href="//index.php?eID=tx_cms_......">
<img width="1600" height="400" border="0" alt="" src="/link/to/my.jpg">
</a>
For some reason, I can't figure out how to get rid of the href-elements, if this special href occurs.
I tried the following:
$(".w-slide a[href='//index.php?eID=']").children('img').unwrap();
didn't do it.
Also I tried this:
$('w-slide a').each(function()
{
if ($(this).attr('href').contains('/eID=tx_cms/'))
{
$(this).children('img').unwrap();
}
}
});
What am I missing? I want to keep the image-tags, but unwrap them, so there are no a tags surrounding them.
You need to check if your url start's with specific string, not to be equal to it:
$(".w-slide a[href^='//index.php?eID=']").children('img').unwrap();
^
by using ^ sign your selector will search for elements that have attribute with values that starts with //index.php?eID=...
Try this
$("a[href*='//index.php?eID=']").children("img").remove();
You can test the code here.
1) You use w-slide class but there is no such class in example.
2) You want to search href EXACTLY like "//index.php?eID=". To search by part use *= matcher like:
$(".w-slide[href*='//index.php?eID']")
Example:
http://codepen.io/alkuzad/pen/xbdEYP

Check if link (not URL) contain some text (.jpg, .gif, .png)

Just to give an Idea what i'm trying to do here's an example code:
$(function(){
if ($('.maybe > div > a.link:contains(".JPG, .jpg, .gif, .GIF")').length) {
alert('hello');
});
I want to check if the content of some links are containing the dot and the letters of all image extensions, like
<div class="maybe">
<div>
<a class="link" href="someURL">thisIsAnImage.jpg</a>
<a class="link" href="someURL">thisIs**NOT**AnImage.pdf</a>
</div>
</div>
<div class="maybe">
<div>
<a class="link" href="someURL">thisIs**NOT**AnImage.zip</a>
<a class="link" href="someURL">thisIsAnotherImage.png</a>
</div>
</div>
The div's and links are generated dynamically by php, so there's no way to know how many links and div's there will be once the page is generated.
How to write the code in a properply way?
Thanks a lot for helping me to resolve the problem.
Here's my first instinct:
$('.maybe .link').each(function () {
if ($(this).text().toLowerCase().match(/\.(jpg|png|gif)/g)) {
console.log("yay I did it");
}
});
Use toLowerCase() on the link text so you don't have to check both lower and upper case. Then use String.match(regex) with a regex group to match all the file extensions.
Hope this helps!
Edit: here's an example in jsfiddle. Open your javascript console to see the output of the console.log statement. http://jsfiddle.net/9Q5yu/1/
I'd suggest:
// selects all the 'a' elements, filters that collection:
var imgLinks = $('a').filter(function(){
// keeps *only* those element with an href that ends in one of the
// file-types (this is naive, however, see notes):
return ['png','gif','jpg'].indexOf(this.href.split('.').pop()) > -1;
});
// I have no idea what you were doing, trying to do, wanting to do or why,
// but please don't use 'alert()', it's a horrible UI:
if (imgLinks.length) {
console.log('hello');
}
The above is a relatively simple, and naive, check; in that it simply splits the href on the . characters and then tests the last element from the array (returned by split()) is equal to one of the elements of the array. This will fail for any image that has a query string, for example, such as http://example.com/image2.png?postValue=1234
Given the clarification in the comments, I'd amend the above to:
var fileTypes = ['png','gif','jpg','gif'],
imgLinks = $('a').filter(function(){
return (new RegExp(fileTypes.join('|') + '$', 'gi')).test($(this).text());
});
References:
JavaScript:
Array.prototype.indexOf().)
[RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
String.prototype.split().
jQuery:
filter()

Replace a href with a js function call

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>

How to check what is after hyphen with jQuery's "Attribute Contains Prefix Selector"

I've got some html like:
<a class="link" href="#>link</a>
<a class="link-0" href="#>link</a>
<a class="link-1 enabled" href="#>link</a>
<a class="link-2" href="#>link</a>
I can select all of those links by:
$('[class|="link"]');
but I find it very difficult to check what is after hyphen, I think about getting classes by attr('class') splitting with split(' ') and checking each class, if it starts with "link" and splitting again with split('-').
Anyone knows better way to do this?
You can use a regular expression:
var matches = element.attr("class").match(/^link-?(\d*)$/);
var whichLink = matches[1];
Interesting that other variations of this selector doesn't match it - perhaps a bug with jquery with hyphens.
$('a[class^="link-"]')
Turns out others work to, just not "word selectors"
$('a[class*="link-"]')

Categories