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>
Related
I have a String and I am detecting some 'urls' and 'closing anchor tags' using regex expression. firstly I am using match function which is returning the list of 'urls' and 'closing anchor tags'. further if my first url is matching with the second url then I dont need to do anything and if it is not matching then I need to replace the closing anchor tag with the same urls. here is the string:-
"This message was sent to ${EmailAddress} because you asked us to keep you up to date with the latest news and offers from the company. If you do not wish to receive these emails, please unsubscribe ${optout()}. You can also change your email preferences on our website logging in at 'a tag' class="footer-link" href="https://sample-website">https://sample-website 'closing a tag'. Please do not reply to this email, as we are unable to respond from this email address. If you need support, please visit the Sample Help Center 'closing a tag'.
var regex3 = new RegExp(/<\/a.?>/gm);
var regex4 = new RegExp(/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|[-A-Z0-9+&##\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&##\/%=~_|$?!:,.]*\)|[A-Z0-9+&##\/%=~_|$])/igm);
var closingATag = footerContentPlainText.match(regex3);
var URLList = footerContentPlainText.match(regex4);
if(URLList != null){
for(var j =0,k=0; j<URLList.length; j++,k++){
if(j+1 != URLList.length) {
if(URLList[j] != URLList[j+1]){
footerContentPlainText =
footerContentPlainText.replace(closingATag[j],"<" + URLList[j] + ">");
}
else if(URLList[j] == URLList[j+1]){
j++;
}
}
else{
if(URLaTags != null){
footerContentPlainText = footerContentPlainText.replace(closingATag[k],"<" + URLList[j] + ">");
}
}
}
}
Although I am handing different scenarios for different type of strings but this is the scenario where I am stuck.
I expect the output, where last 'closing a tag' should be replaced by 3rd url i.e "https://support.samplewebsite.com/samplename".
Here I am not able to write a tag in actual format so I have used just text in place of the same
please help
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"].
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
Let's say I'm on www.forum.com, and, other than the homepage, the URL always has all kinds of additional text, for example, www.forum.com/post1/oh-yeah or www.forum.com/post999/oh-baby but I want to create an if statement that excludes everything other than www.forum.com, how do I do this?
In other words, how to do this:
if ( href.indexOf('forum.com') === 'forum.com' ){
console.log('href value is exactly forum.com, with no additional string');
} else {
console.log('href url contains more than just forum.com');
}
Gracias.
When you invoke the href.indexOf('forum.com') The result is an integer. In a case you get -1, it is because it is non existent.
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.
For more information
So instead of (href.indexOf('forum.com') === 'forum.com') you need to do (href.indexOf('/') == -1) which would mean that there is nothing after www.forum.com
if (href.indexOf('/') == -1) {
console.log('href value is exactly forum.com, with no additional string');
} else {
console.log('href url contains more than just forum.com');
}
This code snippet may help
href = "www.forum.com/test-1";
if (href.indexOf('/') == -1) {
document.getElementById("test").innerHTML = "href value is exactly forum.com, with no additional string";
} else {
document.getElementById("test").innerHTML = "href url contains more than just forum.com";
}
href = "www.forum.com";
if (href.indexOf('/') == -1) {
document.getElementById("test1").innerHTML = "href value is exactly forum.com, with no additional string";
} else {
document.getElementById("test1").innerHTML = "href url contains more than just forum.com";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">Test</p>
<p id="test1">Test</p>
The answers you have here so far are all good. I just going to include something else you might want to consider. If you are trying to grab the url and then look for anything after the hostname, you might want to simply check like this:
if(window.location.pathname != '' || window.location.search != ''){
//stuff after the current url
}
window.location.pathname will handle both examples you provided. If your url has query strings (things with ? in them), then window.location.search will handle that.
This will be another good solution.
var href="www.forum.com";
//ADDED href.indexOf("www.forum.com")==0 for extra verification
if (href.match("www.forum.com$") && href.indexOf("www.forum.com")==0) {
alert("ONLY URL");
}
else
{
alert("URL CONTAINS SOMETHING EXTRA");
}
WORKING FIDDLE
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.