This checks "if we are on movies.php page":
if (location.href.match(/movies.php/)) {
// something happens
}
how to add for this (like or) "if we are on music.php page"?
I assume you mean you want to see if you are on movies.php or on music.php? Meaning you want to do the same thing if you are on either?
if (location.href.match(/movies\.php/) || location.href.match(/music\.php/)) {
// something happens
}
Or if you want to do something different, you can use an else if
if (location.href.match(/movies\.php/)) {
// something happens
}
else if(location.href.match(/music\.php/)) {
// something else happens
}
Also, instead of using match you can use test:
if (/movies\.php/.test(location.href) || /music\.php/.test(location.href)) {
// something happens
}
Based on paulj's answer, you can refine the regular expressions in if statement that checks to see if you are on either page, to a single regular expression:
/(music|movies)\.php/
How about ..
if (/(movies\.php|music\.php)/.test(location.href)) {
// Do something
}
Or even better...
if (/(movies|music)\.php/).test(location.href)) {
// Do something
}
Note the \., this literally matches "a single period" where as in regex . matches any character, thus these are true, but probably not what you want...
if (/movies.php/.test('movies_php')) alert(0);
if (/movies.php/.test('movies/php')) alert(0);
The following improves on previous answers in a couple ways ...
if (/(movies|music)\.php$/.test(location.pathname)) {
var pageName = RegExp.$1; // Will be either 'music' or 'movies'
}
Provides the name of the page (sans .php extension) via the RegExp.$1 property
Using location.pathname eliminates extraneous hits on possible query parameters (e.g. "...?redirect=music.php")
Use of regex '|' operator combines tests into a single regex (particularly good if you have lots of pages you want to match)
Use of regex '$' operator constrains match to end of pathname (avoids extraneous hits in the middle of a path. Not very likely in your example, but good practice)
Related
I am using the the following function in javascript.
function chknumber(a) {
a.value = a.value.replace(/[^0-9.]/g, '', '');
}
This function replaces any non numeric character entered in a textbox on whose onkeyup i have called the above function. The problem is it allows this string as well
1..1
I want the function to replace the second dot character as well. Any suggestions will be helpful.
I don't advocate simplistically modifying fields while people are trying to type in them, it's just too easy to interfere with what they're doing with simple handlers like this. (Validate afterward, or use a well-written, thoroughly-tested masking library.) When you change the value of a field when the user is typing in it, you mess up where the insertion point is, which is really frustrating to the user. But...
A second replace can correct .. and such:
function chknumber(a) {
a.value = a.value.replace(/[^0-9.]/g, '').replace(/\.{2,}/g, '.');
}
That replaces two or more . in a row with a single one. But, it would still allow 1.1.1, which you probably don't want. Sadly, JavaScript doesn't have lookbehinds, so we get into more logic:
function chknumber(a) {
var str = a.value.replace(/[^0-9.]/g, '').replace(/\.{2,}/g, '.');
var first, last;
while ((first = str.indexOf(".")) !== (last = str.lastIndexOf("."))) {
str = str.substring(0, last) + str.substring(last+1);
}
if (str !== a.value) {
a.value = str;
}
}
Can't guarantee there aren't other edge cases and such, and again, every time you assign a replacement to a.value, you're going to mess up the user's insertion point, which is surprisingly frustrating.
So, yeah: Validate afterward, or use a well-written, thoroughly-tested masking library. (I've had good luck with this jQuery plugin, if you're using jQuery.)
Side note: The second '' in your original replace is unnecessary; replace only uses two arguments.
try with match method if your input is "sajan12paul34.22" the match function will return a array contain [12 , 34.22]
the array index [0] is used for getting first numeric value (12)
function chknumber(a) {
a.value = a.value.match(/[0-9]*\.?[0-9]+/g)[0];
}
I am having an issue checking for the URL in the pages on my site.
This is what I have.
Checking for the exact string works well:
var url = location.pathname;
if ("url:contains('texas-ignition-interlock')") {
$("body").addClass("texas-ppc-page");
}
But when I have page url with similar words, both classes were added to both pages.
var url = location.pathname;
if ("url:contains('texas-ignition-interlock-device')") {
$("body").addClass("texas-ppc-device-page");
}
I also tried indexOf, and is didn't work do to the pages with similar names.
This is what I tried, and this works for the first example. Second example will have the first class added too.
if (window.location.href.indexOf("texas-ignition-interlock") > -1) {
$("body").addClass("texas-ppc-page");
}
if (window.location.href.indexOf("texas-ignition-interlock-devices") > -1) {
$("body").addClass("texas-ppc-device-page");
}
Now, I can still use the indexOf version. I would simply target the stuff on one page using the class .texas-ppc-page, and on the second page I would target using both classes of .texas-ppc-page.texas-ppc-device-page.
Is there a better way of doing this with JS or jQuery?
You can use split("/") to split location.pathname into string arrays.
location.pathname will be similar to /questions/41968769/checking-for-exact-url so by splitting this string with "/" will result into
["", "questions", "41968769", "checking-for-exact-url"]
now you can perform indexOf("") and it will return non -1 value if string matched exactly, like in this case if i do indexOf("url") function will return -1, and if i do indexOf("checking-for-exact-url") it will return 3.
If you prefer to examine the strings similarly to how you were, you can leverage a regex, via .test as seen below with the placeholders ^ and $, for start and end, respectively. Otherwise, indexOf will match even a portion of the string. Check out the following...
var url = 'texas-ignition-interlock-devices';
console.log(/^texas-ignition-interlock$/.test(url)); // false
console.log(/^texas-ignition-interlock-devices$/.test(url)); // true
I want to trigger a digital marketing tag on every page which falls under a particular URL path, say example.com/sachin under the sachin directory.
I've tried if (location.href === 'example.com/sachin.*/') but somehow the condition doesn't seem to work.
What will be the correct if condition for location.href if I want to cover all different resources with in the URL path say under sachin directory?
I presume you want to check if the URL contains example.com/sachin. It's highly rarely that any URL ever would contain 4 forward-slashes but what you would do is utilize indexOf.
if(location.href.indexOf("example.com/sachin/") != -1){
//Do something
}
This basically says, if "example.com/sachin/" is found somewhere in the given string(in location.href in this case) on an indexposition that is not -1(which means that it doesn't exist), then execute.
You need to use Regular Expressions to match needed resources.
Something like that:
if(location.href.match(/^http:\/\/example.com\/sachin\//)){
//your staff here
}
Another approach to check for a specific directory in a url.
function urlContains(url, value) {
return ~url.indexOf(value);
}
if (urlContains(location.href, "/sachin/")) {
// found
} else {
// not found
}
The indexOf method checks a string for the value that is passed and returns -1 if a result was not found.
Instead of checking for == -1 or != -1 you can use the Bitwise NOT operator ~ to convert -1 to 0, which is a falsy value, non-zero values are treated are truthy values in javascript.
if(kword == term){
$(this).trigger('click');
}
The case is if the kword is "car" and the term is "cars", I would want that to be a positive match.
Currently I'm looking at an exact match. As I'm a novice at jquery I don't know how to do this. Can anyone point me to the right direction?
You can use indexOf() to find the string inside another
if(term.indexOf(kword)>-1){
//code
}
If you need to simply compare a string variable with a different string variable with an 's' in the end, you can go with following code:
if (term === kword + 's') {
...
}
If you need to check specifically if terms is a plural version of kword, you would need much larger implementation, featuring pluralize function (that you need to implement or search for a library):
if (term === pluralize(kword)) {
...
}
function pluralize(word) {
//implement function
}
If that doesn't not answer your question, please be more clear about what you need to do.
As #Anton said, you can use indexOf(), it returns the position of the first occurrence of a specified value in a string otherwise returns -1 if the value to search for never occurs. Also note that this method is case sensitive.
Basically I was playing around with an Steam bot for some time ago, and made it auto-reply when you said things in an array, I.E an 'hello-triggers' array, which would contain things like "hi", "hello" and such. I made so whenever it received an message, it would check for matches using indexOf() and everything worked fine, until I noticed it would notice 'hiasodkaso', or like, 'hidemyass' as an "hi" trigger.
So it would match anything that contained the word even if it was in the middle of a word.
How would I go about making indexOf only notice it if it's the exact word, and not something else in the same word?
I do not have the script that I use but I will make an example that is pretty much like it:
var hiTriggers = ['hi', 'hello', 'yo'];
// here goes the receiving message function and what not, then:
for(var i = 0; i < hiTriggers.length; i++) {
if(message.indexOf(hiTriggers[i]) >= 0) {
bot.sendMessage(SteamID, randomHelloMsg[Math stuff here blabla]); // randomHelloMsg is already defined
}
}
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my English isn't awesome, ikr)
Thanks in advance. If I wasn't clear enough on something, please let me know and I'll edit/formulate it in another way! :)
You can extend prototype:
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
and do:
var foo = "hia hi hello";
foo.regexIndexOf(/hi\b/);
Or if you don't want to extend the string object:
foo.substr(i).search(/hi\b/);
both examples where taken from the top answers of Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my > English isn't awesome, ikr)
Actually, regex is for any old pattern matching. It's absolutely useful for this.
fmsf's answer should work for what you're trying to do, however, in general extending native objects prototypes is frowned upon afik. You can easily break libraries by doing so. I'd avoid it when possible. In this case you could use his regexIndexOf function by itself or in concert with something like:
//takes a word and searches for it using regexIndexOf
function regexIndexWord(word){
return regexIndexOf("/"+word+"\b/");
}
Which would let you search based on your array of words without having to add the special symbols to each one.