You do not need jQuery for this. Just use regex in Javascript.
if(/^#/.test(href)) { // .test() returns a boolean
/* do not run AJAX function */
} else {
/* run the AJAX function */
}
Explanation:
^# is the regex. // is where you wrap your regex in. ^ means at the beginning of the string and # is what you are looking for. .test() is a javascript function that executes the regex on a given string and return a boolean value.
Read up: RegExp.prototype.test() - JavaScript | MDN
Update 1:
In case if the href is not starting with a # but it still points to the same webpage, your problem is reduced to checking if a string is a substring of another string. You can make use of window.location.href and .indexOf() to achieve this:
if(href.indexOf(window.location.href) > -1) {
/* do not run AJAX function */
} else {
/* run the AJAX function */
}
window.location.href returns the URL of the webpage that you are on and href.indexOf(window.location.href) checks if window.location.href is substring of href;
Example: https://www.example.com/page1 is a substring of https://www.example.com/page1#myDiv
Read up:
Update 2:
Good find by @Tib. My code in update above was not checking if the hostnames are the same. I have fixed it below:
if(<hostnames are the same>) { // make use of window.location.hostname here to get hostname of current webpage
if(href.indexOf(window.location.href) > -1) {
/* do not run AJAX function */
} else {
/* run the AJAX function */
}
} else {
/* do not run AJAX function */
}