jQuery VAR in IF statement usage - javascript

I am sure that this will be a simple solution for someone well versed in jquery.
I am wanting to pass the path name into the if statement so
http://address.com/catalog/product <= catalog then gets passed into the if statment.
if (/\/catalog\//.test(window.location)) {
jQuery('#name-div').hide();
}
so it hides a div if its a child of http://address.com/catalog
var url = location.pathname.split("/")[1];
if (/\/url\//.test(window.location)) {
jQuery('#name-div').hide();
}

As I read your question, what you need is to create a RegExp object from a string since your want to pad with / characters:
var url = location.pathname.split("/")[1],
re = new RegExp('/' + url + '/'); // Create RegExp object from padded string
if (re.test(window.location)) {
jQuery('#name-div').hide();
}

You basically have the answer to your own problem.
$(function(){
var url = window.location.href;
if( /catalog/i.test(url) )
$('#name-div').hide();
});
Unless you have other URLS with catalog in them, there's no reason to dissect the URL any further. Just make sure you select your element after the DOM is ready as I did in my example.

you can do it in many way like:
if( window.location.indexOf(url) !== -1 )
or
if( window.location.search( /url/ig ) )
or
if( window.location.match( /url/ig ).length > 0 )
In this examples you don't even need to use jQuery. It is just normal javascript.

Related

How to modify end of URL using jQuery or javascript?

Have an URL of type:
https://example.com/some/text/1,2,3,5
Need to replace the 1,2,3,5 part with some different parameters like 2,4,6.
Can do it in code by saving the first part of the URL example.com/some/text/ in the data property but that seems messy so. I'd like to do it through REGeX or via similar method so that don't have to save partial URL anywhere.
You could substring it to replace it, or you could break the url apart, get rid of the end, add the new ending, and then join it back up.
var test0 = 'https://example.com/some/text/1,2,3,5';
console.log( test0.slice( 0, test0.lastIndexOf( '/text/' ) + 6 ) + '2,4,6' );
var test = 'https://example.com/some/text/1,2,3,5';
//get rid of the "1,2,3,5"
var tokens = test.split( '/' ).slice( 0, -1 );
//add the new ending
tokens.push( '2,4,6' );
console.log( tokens.join( '/' ) );
Following the #Joshua Moore's link I ended up doing this:
var oldUrl = 'https://example.com/some/text/1,2,3,5';
var newParameters = '2,4,6';
var newUrl = oldUrl.substr(0, oldUrl.lastIndexOf('/')+1) + newParameters;

Javascript - Search for first string after Domain

I have bought a chat plugin and only want to show the plugin symbol on the following pages:
https://stackoverflow.com/en/hello.html
https://stackoverflow.com/fr/hello.html
But not show it on:
https://stackoverflow.com/de/hello.html
What I'v got so far is:
It works, but the problem is when I have a domain that contains en or fr somewhere else in the domain, the chatsymbol is also show. So I need to check if the first string after the domain is en or fr.
Can anybody help?
<script type="text/javascript">
url = window.location.href;
if( url.match(/en|fr/) ) {
document.write('<script id="sb-php-init" src="supportboard/php/sb.php">')
}
</script>
window.location has a lot of utility properties that you can use. Since you do not want domain, you can choose to use pathname. This will give you everything after domain. So for your example, pathname would return /en/hello.html
Now that you have the path, you just have to ignore first character and the look for first / and you have your first path, which in your case would be en.
window.location.pathname.substring(1).split('/')[0]
Now you can just create a list of regions you want to allow and check if current region exists in this
Change your regular expression to include /en/ or /fr/.
This will require you escape the forward-slash, like so:
<script type="text/javascript">
url = window.location.href;
if( url.match(/\/en\/|\/fr\//) ) {
document.write('<script id="sb-php-init" src="supportboard/php/sb.php">')
}
</script>
I can do that as follow:
var arr = window.location.href.split('/');
var isEnOrFr = arr[3].startsWith('en') || arr[3].startsWith('fr')
As #RobbieMilejczak pointed out, this approach needs a additional code:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
Hope this helps!
if (location.pathname.split('/')[1]) {
// your logic here
}
You are able to split the path name of the current URL into an array. For example: stackoverflow.com/posts/48062042/edit will be transformed into ["", "posts", "48062042", "edit"].

How to create dynamic regex in javascript

I want to use $htppBackend to mock some service. My problem is some of service url have parameter, ex: http://domain/service1?param1=a&param2=b
I need an regex which can reconize http://domain/service1<whatever> is correct for http://domain/service1?param1=a&param2=b. One thing, the first part http://domain/service1 is not a constant, it can be http://domain/service2/sth/anything.
Please help. Thanks.
Edit:
I put my code here to make it easy to understand.
I have 4 api urls:
angular
.module('moduleName')
.constant('getApi', {
attrList: 'http://domain/setup/attrList',
eventList: 'http://domain/setup/eventList',
vcList: 'http://domain/api/list1',
getRaDetails: 'http://domain/abc/getDetails?raId={0}&bookId={1}'
});
With attrList, eventList and vcList, they are ok with
$httpBackend.whenGET(getApi.attrList).respond(responseObject);
$httpBackend.whenGET(getApi.eventList).respond(responseObject);
$httpBackend.whenGET(getApi.vcList).respond(responseObject);.
But the last one getRaDetails, it doesn't work with
$httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); because raId and bookId have different value each times.
Now I need a regex to make this rule - $httpBackend.whenGET(getApi.getRaDetails).respond(responseObject); works with all raId and bookId value.
Hope it can explain my question more clearly. Thanks
I need an regex which can reconize http://domain/service1 is
correct for http://domain/service1?param1=a&param2=b
I don't think a regex is required here. Just simply check
var stringPattern = "http://domain/service1";
var input = "http://domain/service1?param1=a&param2=b";
if ( input.indexOf( stringPattern ) == 0 )
{
alert( "correct" );
}
else
{
alert( "Incorrect" );
}
So, if you are parsing Urls, it's best to use the URL object in JavaScript:
var input = 'http://domain/abc/getDetails?raId={0}&bookId={1}';
var test = 'http://domain/abc/getDetails';
var testUrl = new URL(test);
var inputUrl = new URL(input);
then test the various bits:
if(testUrl.pathname === inputUrl.pathname){
// they both have /abc/getDetails as the path
}
This's my working code:
_(getApis).each(function (api) {
var val = api.value.split('?')[0].replace(/\//g, '\\/'),
reg = new RegExp(val);
$httpBackend.whenGET(reg).respond(dummy[api.key]);
});
Thanks all.

JavaScript .search() for a URL with wildcard using RegEx

I'm building a site that is a portfolio of projects. I have some pagination that allows you to go next/previous project.
I want to run some animations when coming to a project, but not when browsing between projects.
My plan is to use the referrer URL to know if you came to a project from another project, and thus not run the animation. But my RegEx is not good, so I'm having trouble.
Here is what I'd like to do (pseudo code)
var refURL = document.referrer;
if( refURL.search('http://www.example.com/work/digital/*') > 0 ) {
// Do not run animation
} else {
// Run animation
}
The important thing, is that "http://www.example.com/work/digital/" should be FALSE, but "http://www.example.com/work/digital/*" should be TRUE.
So, what's the RegEx to do that?
Thanks!
I think you are looking for this:-
var refURL = document.referrer;
if( refURL.search('http://www.example.com/work/digital/(.*)') > 0 ) {
// Do not run animation
} else {
// Run animation
}
In other way, you can use indexOf()
refURL.indexOf("http://www.example.com/work/digital/");
if(refURL.indexOf("http://www.example.com/work/digital/") > -1) {
// Do Your Stuff
}
(.*) matches 0 or more characters whereas (.+) matches 1 or more characters
Also RegExp in JavaScript does not need to be enclosed, so just type
var exp = /pattern/modifiers
For more details visit: http://www.w3schools.com/jsref/jsref_obj_regexp.asp
My idea for your problem is to try something like:
var refURL = document.referrer;
if (refURL.search(/^http:\/\/www.example.com\/work\/digital\/(.+)$/i) >= 0) {
// Do not run the animation
} else {
// Run the animation
}
can use regex and in javascript
var searchin = item.toLowerCase();
var str = "*abc*";
str = str.replace(/[*]/g, ".*").toLowerCase().trim();
return new RegExp("^"+ str + "$").test(searchin);
var re = /^http:\/\/www.example.com\/work\/digital\/.+$/i;
console.log('http://www.example.com/work/digital/x'.search(re));
console.log('http://www.example.com/work/digital/'.search(re));

Javascript say if a folder is child of another

I have these strings which are addresses of files and folder:
../../../folder1/sub1/sub12/
../../../folder1/
../../../another-folder/
I want to compare them using javascript - possibily jquery - to see if for example string 1 have a part egual to string 2 but something more saying that string 1 is child of string 2.
How can i do this?
you could try something like the following
var path1 = "../../../folder1/";
var path2 = "../../../folder1/sub1/sub12/";
if (path2.indexOf(path1) != -1){
//path2 is a sub of path 1
}
In case your string can contain also absolute paths or paths containing .. not only at the beginning I would recommend checking if .indexOf return 0 instead of anything that is not -1.
It can help with cases like.
var path1 = "/rootFolder/";
var path2 = "../folder/rootFolder/";
if (path2.indexOf(path1) === 0) {
console.log("You want this"); // won't get executed => good
}
if (path2.indexOf(path1) !=-1) {
console.log("You don't want this"); // will get executed => bad
}
if(string1.indexOf(string2) != -1){
//string2 is present in string1
}
else{
//string2 is not present in string1
}
You can use the indexOf method to find whether one string is a part of another string.
From w3schools documentation:
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.
var test = "../folder/subfolder1";
var test2 = "../folder";
if (test.indexOf(test2) !=-1) {
alert(test + " is a subfolder of " + test2);
}

Categories