Javascript - Search for first string after Domain - javascript

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"].

Related

Regex check against referrer URL string

var orig = document.referrer; // Incoming URL
var check = new RegExp("boxes", "gi"); // Literal string, global + case insensitive.
// console.log(check);
if (orig.indexOf(check) > -1) {
console.log('you came from the box section');
} else {
console.log('you DIDNT come the box section');
}
Hi Guys,
I have a 'boxes' category on a site, where all box items have 'boxes' in the URL. A particular item from another category needs to be able to check whether or not the user came from a 'boxes' item. (This is an interim solution as I only have skin-level access).
When logging 'check', I get '/boxes/gi', which should be working when checking within indexOf, as a valid regex string.
I am not too sure why I can not get this to properly check, as the result is only ever that the user didn't come from the 'boxes' section.
I have a lot to learn, so in advance, I greatly appreciate any help.
Thanks!
You can use string variable instead of regex
var orig = document.referrer; // Incoming URL
// console.log(check);
if (orig.indexOf("boxes") > -1) {
console.log('you came from the box section');
} else {
console.log('you DIDNT come the box section');
}
indexOf does not accept a regex as argument. You either use your regex with search, or use indexOf with a string.
orig.toLowerCase().indexOf("box") > -1
// or
orig.search(check) > -1
You can parse the referrer URL into a link element and retrieve its pathname. You should also probably check the hostname to make sure it's from your own site:
var url = document.createElement('a');
url.href = document.referrer;
var comingFromBoxes = url.hostname === 'yoursite.com' && url.pathname.indexOf('/boxes') === 0;
Note: the referrer is not a reliable value by any means and should not be considered as such.
You can use match() with the regex to perform your logic.
$(document).ready(function(){
var url = "www.someurl.com/boxes/gi/abc";
var regex = /\/boxes\/gi/g;
var mtch = url.match(regex);
if(mtch !== null){
alert('url has the value');
}
else{
alert('url does not have the value');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to check if string contains '?' using javascript

I'm trying to check if an url contains a query string or not.
Lets say we have these two url's.
http://localhost:3000/userbookings/list
http://localhost:3000/userbookings/list?resource=de
My string is called fullPath, and I need to check if it contains the ?, so I know if its a query string or not.
Have tried with the following code:
if (fullPath.indexOf("?") > -1){
content = fs-readFileSync('http://localhost:3000/userbookings/list1');
}
else {
content = fs.readFileSync(fullPath);
}
Your way should work too but if you want in the future to use more complex qualifiers you could start using regular expressions:
var pattern = /\?/g;
var found = fullPath.match(pattern) != null;
alert(found);
this help you :
<html>
<head>
</head>
<body>
<script>
var str = "this is ?text";
var patt = /\?/gi;
if(str.search(patt)!=-1)
alert("Found");
else
alert("No found");
</script>
</body>
</html>
Like this:
if (str.indexOf("?") >= 0)
Or,
if (/\?/i.test(str))
Or,
if(str.includes('?'))
Please note that String.includes is an EcmaScript 6 feature and may not work in some browsers.
I think your goal is just to check if there's a php get variable right??
if(document.localtion.search != "") {
// Your code
}
The document.location.search will be "?resource=de" if you visit the url
http://localhost:3000/userbookings/list?resource=de
And it will be "" if you visit the url
http://localhost:3000/userbookings/list
Answer #2
check = document.location.split("?");
if(check.length > 1) {
//do your code
}
splitting the http://localhost:3000/userbookings/list?resource=de url using "?" will be splitted by 2.
And splitting the http://localhost:3000/userbookings/list url using "?" wil result by 1.
Answer #3
check = fullpath.replace("?","");
if(check != fullpath) {
//do your code
}
Removing the "?" in the full path. If the check is the same as fullpath then it doesn't have a "?"
I think this might help you out. Feel free to comment

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.

How to know if a url has parameters in javascript

I want to check if a url has parameters or it doesn't, so I know how to append the following parameters(with ? or &). In Javascript
Thanks in advance
Edit:
With this solution it works perfectly:
myURL.indexOf("?") > -1
Split the string, and if the resulting array is greater than one and the second element isn't an empty string, then at least one parameter has been found.
var arr = url.split('?');
if (arr.length > 1 && arr[1] !== '') {
console.log('params found');
}
Note this method will also work for the following edge-case:
http://myurl.net/?
You could also match the url against a regex:
if (url.match(/\?./)) {
console.log(url.split('?'))
}
Just go through the code snippet, First, get the complete URL and then check for ? using includes() method.includes() can be used to find out substring exists or not and using location we can obtain full URL.
var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url = window.location.href; // Returns full URL (https://example.com/path/example.html)
var origin = window.location.origin; // Returns base URL (https://example.com)
let url = window.location.href;
if(url.includes('?')){
console.log('Parameterised URL');
}else{
console.log('No Parameters in URL');
}
You can try this:
if (url.contains('?')) {} else {}
You can try this also.
var url = YourURL;
if(url.includes('?')) {} else {}
url.includes('?') Will return true if ? exist in the URL.

jQuery VAR in IF statement usage

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.

Categories