JS - What is the difference here? - javascript

I'm a newbie to JS and it would be extremely useful to know what the differenece is between the following two if statement conditions...
First condition (not actually working):
if ( window.location.pathname == '/#register' ) {
// Code
}
Second condition:
if (document.URL.indexOf("#register") >= 0) {
// Code...
}
FYI, this would help me solve a bug I'm experiencing here

The first checks for an exact match. And it does it on the pathname, which doesn't include the hash, so it probably doesn't do what you want.
The second one checks the string contains "#register", so the full path could be bigger, like /#register_or_not or /some/other/path#register
Probably your best option would be to do a regex pattern match on the URL, to ensure that the hash it matches is ONLY 'register', while allowing the rest of the URL to be whatever:
if (document.URL.match(/.*#register$/)) {

The second just check if the url contains #register, the first the url path, you can do it also with location.hash
if(location.hash=='#register') { //....

The first one performs an exact match between window.location.pathname and /#register. The second one looks for #register anywhere in document.URL.

This if block check the strings whether they are equal or not
if ( window.location.pathname == '/#register' ) {
// Code
}
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
if (document.URL.indexOf("#register") >= 0) {
// Code...
}

Related

return true if only there is exact include

Using includes method we get true for all of these logs:
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('listen_again_long')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('listen_again')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('listen')); // true
But we know only the first log should return true because we have exactly listen_again_long inside the longer string.
if we consider this part fixed: https://example.com/test/media/instructions/
How we can only return true for the first one and false for the rest of the logs?
You are actually looking for a certain string enclosed in /, so one option would be to simply include both / in the argument you are passing to String.prototype.includes():
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('/listen_again_long/'));
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('/listen_again/'));
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('/listen/'));
You could also do the same thing using RegExps and RegExp.prototype.test():
console.log(/\/listen_again_long\//.test("https://example.com/test/media/instructions/listen_again_long/1.mp3"));
console.log(/\/listen_again\//.test("https://example.com/test/media/instructions/listen_again_long/2.mp3"));
console.log(/\/listen\//.test("https://example.com/test/media/instructions/listen_again_long/3.mp3"));
In both cases you could replace /listen_again_long/ with the whole thing if you want to make sure the match doesn't happen in a different place:
"...".includes("https://example.com/test/media/instructions/listen_again_long/");
Or, with RegExp:
/https:\/\/example.com\/test\/media\/instructions\/listen_again_long\//.test("...");
You'll have to extract the substring you want to compare against your parameter and then do a straight === comparison.
var url = <your passed in mp3 file>;
var s = "https://example.com/test/media/instructions/"
var substring = url.substring(url.indexOf(s) + url.length);
substring = substring.substring(0, url.indexOf("/");
substring === "listen_again_long"

jQuery - Only carry out action if url doesn't contain any parametres

I have a function that runs only if an attribute is blank:
if (!$(".main-image").attr("src")) {
loadImageAjax();
}
But I also only want it to run IF the url doesn't contain any parametres.
So only if the domain is simply: www.domain.com and not www.domain.com/?image=33
You can check for the existence of the ? character. More often than not, if there are going to be url parameters, the ? character will also exist.
if ( url.indexOf("?") < 0 ) {
// code for 'no parameters' goes here
}
If your URLs use a different pattern you will need a function that knows how to check where the parameters are. (Stack Overflow URLs are an example of URLs that do not follow the ?a=1&b=2 pattern).
If you want to disallow everything that is not "www.domain.com", you can check for the existence of the "/" character.
var indexOfSlash = url.indexOf("/");
// the second check is just in case you want to allow "www.domain.com/"
if ( indexOfSlash < 0 || !url.substring(indexOfSlash + 1) ) {
// code for 'no parameters' goes here
}

JavaScript Replace function check

I am doing a java script replace as :
var featureTitle;
featureTitle = row.cells[1].text();
if (!featureTitle.indexOf('*') != -1)
{
featureTitle = featureTitle.replace('*', '');
}
Is if (!featureTitle.indexOf('*') != -1) needed check here??
OR replace will take care of it?
replace will do nothing if the asterisk does not exist, so it's safe to call without the check first.
Speaking of which, the check has a bug which makes the code as a whole behave incorrectly:
if (!featureTitle.indexOf('*') != -1) // what's that ! in front doing?
Since !featureTitle.indexOf('*') is always true or false, this condition will always succeed (both booleans compare unequal to -1).
Here is the referenced JSFiddle for you
if (!featureTitle.indexOf('*') != -1){...}
is not mandatory to place, you can do .replace() directly
var featureTitle;
featureTitle = row.cells[1].text();
featureTitle = featureTitle.replace('*', '');
There is no need of that if statement. I think .replace() will take care of it(if *exists it will replace it else no action). If you want to replace all the * in the string then use \g global attribute.
featureTitle = featureTitle.replace(/*/g,'');
replace will work on first occurence of '*'. If there is none, then nothing will be replaced, therefore "if" is not needed

CodeMirror - Using RegEx with overlay

I can't seem to find an example of anyone using RegEx matches to create an overlay in CodeMirror. The Moustaches example matching one thing at a time seems simple enough, but in the API, it says that the RegEx match returns the array of matches and I can't figure out what to do with it in the context of the structure in the moustaches example.
I have a regular expression which finds all the elements I need to highlight: I've tested it and it works.
Should I be loading up the array outside of the token function and then matching each one? Or is there a way to work with the array?
The other issue is that I want to apply different styling depending on the (biz|cms) option in the regex - one for 'biz' and another for 'cms'. There will be others but I'm trying to keep it simple.
This is as far as I have got. The comments show my confusion.
CodeMirror.defineMode("tbs", function(config, parserConfig) {
var tbsOverlay = {
token: function(stream, state) {
tbsArray = match("^<(biz|cms).([a-zA-Z0-9.]*)(\s)?(\/)?>");
if (tbsArray != null) {
for (i = 0; i < tbsArray.length; i++) {
var result = tbsArray[i];
//Do I need to stream.match each element now to get hold of each bit of text?
//Or is there some way to identify and tag all the matches?
}
}
//Obviously this bit won't work either now - even with regex
while (stream.next() != null && !stream.match("<biz.", false)) {}
return null;
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), tbsOverlay);
});
It returns the array as produced by RegExp.exec or String.prototype.match (see for example https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match), so you probably don't want to iterate through it, but rather pick out specific elements the correspond to groups in your regexp (if (result[1] == "biz") ...)
Look at implementation of Code Mirror method match() and you'll see, that it processes method parameter for two types: string and RegExp.
Your constant in
stream.match("<biz.")
is of string type.
Define it in RegExp type:
tbsArray = /<biz./g
Thus, your stream will be matched with RegExp.

Exact string match with javascript regex

I'm struggling with what is probably a very simple regex problem. I'm working on a simple prototype and need to know what page I'm on, so I don't reload it if the user clicks a menu widget to navigate to the same view.
I have two URLs the user can switch between:
http://localhost/TestMVC/Larry/LarryTiles
http://localhost/TestMVC/Larry/LarryTilesList
The URLs can also have some trailing querystring items, like this:
http://localhost/TestMVC/Larry/LarryTilesList?filterValue=servers
LarryTiles is giving me the problem. "/\bLarryTiles\b/" worked on Friday (after answers from other questions here) but this doesn't match now. :)
I need to find exactly the strings "LarryTiles" and "LarryTilesList" in these two URLs but can't quite figure out how to do that. The URL changes between my local machine and the various servers where it's hosted, so I can't rely on position.
EDIT: added the example with a trailing querystring, which I'd forgotten. Sorry :(
You can get the last path segment of an URL like this:
function getLastPathSegment(url) {
var match = url.match(/\/([^\/]+)\/?$/);
if (match) {
return(match[1]);
}
return("");
}
// returns "LarryTiles"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTiles");
// returns "LarryTilesList"
getLastPathSegment("http://localhost/TestMVC/Larry/LarryTilesList");
So, you could do this:
var endPath = getLastPathSegment(window.location.pathname);
if (endPath == "LarryTiles") {
// some code
} else if (endPath == "LarryTilesList") {
// some code
} else {
// some code
}
You can use this code:
str = 'http://localhost/TestMVC/Larry/LarryTiles?filterValue=servers';
if (str.match(/\/([^\/?]+)(?=\/$|\?|$)/)) {
if (match[1] == 'LarryTiles')
alert('LarryTiles found');
else if (match[1] == 'LarryTilesList')
alert('LarryTilesList found');
}
Seems like what you explained works, otherwise try this: http://jsfiddle.net/Wfz9d/
Do you have a case-sensitivity issue?

Categories

Resources