jquery href .indexOf, how to exclude - javascript

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

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

double expression using match function in javascript

path = google.com/page/4/post.php
and some time it will another path like google.com/blog/page/ which contains the string 'page' in the URL.
path.match(/page/gi) but second path is true, how to skip that?
is it like this?
if(path.match(/page/gi) && !path.match(/page/gi)){
}
Yes, you can use !path.match.
This actually works as I understand is expected:
if(path.match(/page/gi) && !path.match(/post/gi)){
console.log('no match');
} else {
console.log('match');
}
JSFiddle

How to replace part of string with another in js?

I'm using js to read an xml file elements and replace some nodes name with another by replacing part of the string, but when running my app nothing happening, that's my code:
$('#dummy').load('cafe.xml',function() {
initialize();
})
function initialize(){
ct=$('menu').children().length;
for(cati==0;cati<=ct-1;cati++)
{
cats[cati]=$('menu').children().eq(cati).prop('nodeName');
// modifing the whitespaces and special characters
var realname = cats[cati];
if(realname.indexOf(".") != -1){
realname.replace(/\./g,' ');
}
if(realname.indexOf("1") != -1){
realname.replace(/\1/g,'\'');
}
if(realname.indexOf("2") != -1){
realname.replace(/\2/g,'&');
}
if(realname.indexOf(":") != -1){
realname.replace(/\:/g,'(');
}
if(realname.indexOf("!") != -1){
realname.replace(/\!/g,')');
}
if(realname.indexOf("0") != -1){
realname.replace(/\0/g,'/');
}
}
replace doesn't change the original string. Try with something like
realname = realname.replace(/.../g, "...");
Anyway, I'd ditch all those if, that are kind of useless given what you're doing.

Categories