Javascript Error: this.replace($foo, ""); - javascript

My sixth line of code does not work. Please help.
function ajax() {
$('a[class="ajax-cw"]').click( function() {
$('#cw').load( this + "?ajax" );
$('#nav li.current').removeClass('current');
var $base = $("base").attr("href"),
$link = this.replace($base, ""); //Line does not work
alert ($link);
return false;
});
};

if you were trying to replace parts of the href contents of the currently clicked link with that of the base object, you have to access the href contents via
var currenthref = $(this).attr('href');
and then use currenthref in the replace line.
$link = currenthref.replace($base, "");
Thre replace function on this will not properly work because it is not a string but rather an object (most likly jquery) that represents the link element you klicked on.

try this:
this.href.replace($base, '');

this in line 6 is the <a /> tag, not the href of that tag. $(this).attr('href').replace($base,"") will perform better.

You need to end the previous line with a semi-colon. You have ended it with a comma.
var $base = $("base").attr("href");

Related

jQuery add class based on parent URL

on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.
However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?
Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"
Here is my jQuery:
var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
if(jQuery(this).attr('href')=== cururl){
jQuery(this).addClass("current-slider-menu");
}
});
EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.
Try this,
Change the class/selectors as per your requirement. This will add a unique class in the li element, now you can style this using css.
$(document).ready(function() {
$(".main_menu li").removeClass('current-slider-menu');
$(".main_menu li>a").filter(function(){
return this.href == location.href.replace(/#.*/, "");
}).parent("li").addClass("current-slider-menu");
});
You're definitely on the right track.
You can grab the currentURL (before the anchor #):
const currentURL = window.location.href.split('#')[0];
Then you can split the currentURL into its constituent folders:
const currentURLArray = currentURL.split('/');
Then, separately, you can grab all the myLinks:
const myLinks = [...document.querySelectorAll('a.rs-layer')];
And finally you can cycle through myLinks and if the name of the folder you want to match does match the name of the equivalent folder in the currentURL, then you can add the .current-slider-menu class:
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
Complete Example:
const currentURL = window.location.href.split('#')[0];
const currentURLArray = currentURL.split('/');
const myLinks = [...document.querySelectorAll('a.rs-layer')];
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
EDITED
try this
var cururl = window.location.href;
jQuery("rs-layer[id|='"+cururl.split('/')[3]+"'] , .rs-layer[href='"+cururl+"']").each(function(){
jQuery(this).addClass("current-slider-menu");
});
I solved it like this instead, skipping the whole idea with text-decoration.
I added an arrow. Finished.
JS:
var url = window.location.href;
var msg = document.getElementById('current-menu-item-arrow');
if( url.search( 'my-word' ) > 0 ) {
msg.style.display = "block";
}
CSS:
#current-menu-item-arrow {display:none;}

Convert all HTML Links to another URL with HTML and Javascript

I am trying get all HTML links in a website's body section within a string and replace them to another link.
Tried something like this but did not work:
var search = "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer";
var replacement = "https://example.com/";
document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)
Where "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer" is the link I want to replace and "https://example.com/" is the link that I want to replace with.
How about this:
$("[href='your link']").attr("href","new link");
Here is a solution with plain javascript as per your question
document.querySelectorAll("[href='" + search + "']").forEach(function(el){
el.href = replacement );
});
If you want to use jQuery, as you tagged, follow the answer of Nir Tzezana
$('body').find('a').each(function(){
$(this).attr('href','your_new_link');
});
or for different href:
$('body').find('a').each(function(){
var ahref = $(this).attr('href');
if ( ahref == 'your_old_link') { /// or ahref.indexOf("your_old_link") >= 0
$(this).attr('href','your_new_link_1');
}else{
$(this).attr('href','your_new_link_2');
}
});
Just use
$("body a[href='https://www.cloudflare.com']").attr("href","https://example.com/");

How to extract a part of a value inside an attribute

I have many hyperlinks with a onclick function which have differents values on this way:
<a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'bikes'});">bikes whatever</a>
<a onclick="Utils.decideOffer('', {'unlockFeature': 'motorcycles'});">another motor</a>
Now when this element is clicked I need to get the values of that array, example: "cars", or "bikes" or "motorcycles".
Don't suggest to get them from the Utils.decideOffer function because I need to get them without edit that file/function. This is how I intend to extract it.
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var optionSelectedValue = ??? ;
}
});
I was thinking on use Regex so can you please help me on the Regex to use on this case?, or if you have another good idea to achieve this it is also welcome!
Try split() like :
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var optionSelectedValue = onclickValue.split(":")[1].split("}")[0];
}
});
it will return the 'cars' or 'bikes' or 'motorcycles' including the quotes
See JSFIDDLE
... or to get the value without quotes as suggested :
optionSelectedValue = onclickValue.split(":")[1].split("}")[0].split("'")[1];
See updated JSFIDDLE
$('a').click(function() {
onclickValue = $(this).attr('onclick');
if (onclickValue.length) {
var re = /(?!: ')+(\w)+(?='})/;
var found = onclickValue.match(re);
var optionSelectedValue = found[0] ;
alert(optionSelectedValue);
}
});
Demo: http://jsfiddle.net/wpjh1ma7/

Extract characters after ?= in link

Can anyone see where I going wrong here, I'm trying to get the last characters after the ?p= in a link and put in a varaible, but the code I'm using returns /.
My code is:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
alert('click detected');
var city = ($('input#hdnCountry').val());
alert(city);
var link = $('a').attr('href');
//var getEqualPosition = link.indexOf('?p='); //Get the position of '='
var getEqualPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(getEqualPosition + 1); //Split the string and get the number.
My link is
»
I think what is happening is its picking up the 1st = .
My theory is this.
1) Detect the click event
2) Get the link that caused the event
3) Extract the value of p,
p can be 1 diget, 2 digets or 3 digets.
Any help would be appreciated, as it seems no sooner do I solve 1 problem then another arises.
Thanks
George
Assuming that p is the only parameter in the URL you can simply split by the = sign:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
var city = $('input#hdnCountry').val();
var number = $(this).attr('href').split('=')[1];
});
The problem is this part:
var link = $('a').attr('href');
That does not select the link that was clicked, unless you happen to be clicking the very first link present in the HTML of the page. What that will do is select all <a> elements, then return the href attribute of the first one.
Inside your event handler, you want to use this to refer to the link that was clicked:
var link = $(this).attr('href');
// or simply
var link = this.href;
Try with this:
link.split('?p=')[1]
String s = "Jecy penny ? like sears";
String[] arr = s.split("\\?");
Added \\ before ?, as ? has a special meaning
String res = arr[0];
May be you are wrong at escape character for ' ? '
check this link Remove all characters after a particular character
Try this: http://jsfiddle.net/7atyG/1/
$(document).on('click', '.dvPagerCities a', function (ev) {
ev.preventDefault();
var link = $(this).attr('href');
var Linkval = link.substr(link.indexOf('=') + 1);
alert(Linkval);
});

How to get the text after the # symbol in a link?

I have a simple link with a hashtag in it. ie:
<a class="page_navigation" href="#something">click</a>
On clicking this, I would like to just end up with the 'something' part (minus the hash) in a var.
So far I have
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
});
Obviously I just end up with '#something' in my href var with the above code, and I understand I could do some kind of regex (not sure how yet) to strip the #, but I wonder if there is an easier way to access this part of the href I'm unaware of, without having to go through some find and replace code.
Any ideas?
Note: I also know I could store the 'something' in a data tag, but I'm trying to keep this code as DRY as possible.
If you know it has a # in it, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = this.href.replace(/^.*#/, "");
});
If you don't know whether it has one it it or not, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = "";
if (this.href.indexOf("#") {
hash = this.href.replace(/^.*#/, "");
}
});
In HTML5, you could use:
this.hash
but that is only for the latest browsers.
var theHash = $(this).prop("hash").substr(1);
Related answer to another question
Demo http://jsfiddle.net/UR3XN/
code
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
var equalPosition = href.indexOf('#'); //Get the position of '#'
var withouthash = href.substring(equalPosition + 1);
alert(withouthash);
});​
You don't need regular expressions for this. You can simply do
var fragment;
if (window.location.hash) {
fragment = window.location.hash;
}
Note that this will pick up the # symbol as well. So,
fragment = "#something"
If you don't want the # symbol, use substring like this:
fragment = window.location.hash.substring(1)
If you want to pick out the hash fragment from an anchor tag, you can do this:
var link = $('#yourAnchor').attr('href');
var fragment;
if (link.indexOf("#") !== -1) {
fragment = link.substr(link.indexOf("#") + 1);
}

Categories