So I have paths such as "/users/2" or "/users/4" or "/users/25" etc and I need to setup an if statement such as:
if(window.location.pathname == "/users/?????") {};
that catches all of these paths.
you could check the indexOf of '/users/'
var pathName = window.location.pathname;
if (pathName.indexOf('/users/') === 0) {
}
I guess if you have just "/users/", and nothing after the 2nd slash your condition would be not satisfied, I suggest something to ensure you have the id of the user (checking the length of the string to be greather than --> the position of the substring to search AND its length added, if it's so --> there must be something after it, which we suppose it's the id...) like this:
var p = window.location.pathname;
if(p.indexOf("/users/") > -1 && p.length > p.indexOf("/users/") + 7) {
...
}
...maybe you can also check if the id after the 2nd slash is a number if needed...
Please use this:
var pathname = window.location.pathname;
if (pathname.startsWith('/users/')) {
// Do stuff here
}
Read more about startsWith method.
Related
I am trying to develop a Javascript code which will suit my website. Here is my code:
jQuery('.hestia-title').click(function() {
var link;
link = location.href;
if (link = "http://www.puslapioguru.eu" || "https://www.puslapioguru.eu" || "www.puslapioguru.eu") {
var element_to_scroll_to = jQuery('.second-title')[0];
console.log("Viskas veikia");
element_to_scroll_to.scrollIntoView();
} else {
window.location.href = "http://www.puslapioguru.eu/";
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This code should determine on what open page it is run, but I encounter a problem with the if statement:
if (link="http://www.puslapioguru.eu" || "https://www.puslapioguru.eu" || "www.puslapioguru.eu")
I want that the if statement would run only if the specific URL would be opened, but now it even runs if the opened page URL is "http://www.puslapioguru.eu/temu-portfolio/". Can someone please help me with this problem?
Each part of || (or &&) has to equate to true/false by itself, ie:
if ((true|false) || (true||false))
so, rather than just use a string, you need to provide something to compare with, in each of the parts around the ||
Secondly, in javascript, if you are comparing a value you need to use == or ===, not =. This gives,
link = location.href;
if (link == "http://www.puslapioguru.eu"
|| link == "https://www.puslapioguru.eu"
|| link == "www.puslapioguru.eu") {
You can make this more flexible, but these are the essential issues with your if.
In this case you might want just location.host instead of location.href as .href is the entire address including any page path or parameters while .host already removes the https:// etc parts for you:
link = location.host;
if (link == "www.puslapioguru.eu") {
Either use a Regular Expression
/^https?:\/\/(?:www\.)?puslapioguru\.eu$/i.test(link); // Exactly on this
// OR
/^https?:\/\/(?:www\.)?puslapioguru\.eu(?:$|\/)/i.test(link); // Any path on this
Or use Array methods to test for your options
const permittedSiteList = [
'http://www.puslapioguru.eu',
'https://www.puslapioguru.eu',
'www.puslapioguru.eu'
];
permittedSiteList.includes(link); // eactly one of these
// OR
permittedSiteList.some(
domain => (link + '/').toLowerCase().startsWith(domain + '/')
); // Any path
If you choose one of these, I also recommend abstracting the RegExp or the Array outside the condition so it is more readable; i.e. the if's condition looks like
if (permittedSiteRegExp.test(link)) {
// ...
}
// OR
if (permittedSiteList.includes(link)) {
// ...
}
// OR in the Array + any path case, also the test function
const isThisDomain = domain => (link + '/').toLowerCase().startsWith(domain + '/');
if (permittedSiteList.some(isThisDomain)) {
// ...
}
Currently, you're performing an assignment in your if statement so you'll get unexpected behaviour
I have a JavaScript function that I want to use to get the current URL and if there is any value after the = then it should placed in a textbox that has an ID of name. However at the moment, when I open the page, the full URL is displayed in the text box, so I want to have some kind of condition where it only displays if there is a value after the only =
function DisplayProdCod(value) {
var URLstring = window.location.href;
if (URLstring.indexOf('=')) {
var ProductCode = URLstring.split("=").pop();
document.getElementById('Name').value = ProductCode;
document.getElementById('Name').style.backgroundColor = #C8C8FF;
}
}
A typical URL could be
http://brmappsvr:7018/Enquiries/CMFRAME.html
or
http://brmappsvr:7018/Enquiries/CMFRAME.html?ProductCode=1BLK970/07
Change the condition to check if returns -1, like so:
function DisplayProdCod(value) {
var URLstring = window.location.href;
if (URLstring.indexOf('=') != -1) {
var ProductCode = URLstring.split("=").pop();
document.getElementById('Name').value = ProductCode;
document.getElementById('Name').style.backgroundColor = #C8C8FF;
}
}
The indexOf function returns -1 when the character you are searching for does not occur in the string. And as every number (except 0) is truthy the condition in your if-condition is met everytime. So you should better check if the index is greater than -1, i.e.
if (URLstring.indexOf('=') > -1) {
...
}
Just do URLstring.split('=') anyway, then check the length of the result. If it's 2, work with result[1], otherwise something went wrong.
Try this
Example
html
<input type="text" id="Name"/>
<input type="button" onclick="DisplayProdCod();" value="click"/>
JS
function DisplayProdCod() {
var URLstring = window.location.href;
alert(URLstring);
if (URLstring.indexOf("=") > -1) {
var ProductCode = URLstring.split("=").pop();
document.getElementById("Name").value = ProductCode;
document.getElementById('Name').style.backgroundColor ="#C8C8FF";
}
}
See the DEMO in this demo i am searching a string "fiddle" you can replace it with "=" in your program
Note:
in your code you are missed a double quotes when you setting a background colour
it should be like below
document.getElementById('Name').style.backgroundColor ="#C8C8FF";
So I am using Node.JS and doing a small multiplayer project.
Of course I'm using JavaScript for a lot of things.
I would like to check if a div contains a certain word and if that certain word matches a variable.
How would I do this with JavaScript?
I want something like:
var teststring = "hi";
if "<div id="test">" contents matches "teststring"
{
}
I also have jQuery so that's an option too!
I'm new to JavaScript so please fire away!
This was my attempt but it didn't work:
var socket = io.connect('http://*');
socket.on('field', function (data) {
if ($("#userid").text().indexOf(data) > -1)
{
window.alert('lol');
console.log(data);
$("#field").html(data);
}
else
{
window.alert("Something has gone wrong with the node server...");
}
});
Just check the contents of the div with the text() function of jQuery, like this:
var teststring = "hi";
if ($("#test").text().indexOf(teststring) > -1)
{
alert("Match!");
}
to get the value of the div you can use
var divValue = $('#test').text();
var teststring = "hi";
and to match with the variable;
if(divValue === teststring ){
alert('Two variables are matching !!');
}
and to search a String contains a substring you can use;
if (divValue.indexOf(teststring ) >= 0)
{
alert('Two variables are matching !!');
}
please visit http://jsfiddle.net/dennypanther/ojmyobL8/
In JavaScript u can do it lyk this :
var teststring = "hi";
var div=document.getElementById('test').innerHTML;
if(div.indexOf(testString) > -1 ){
// your code goes here
}
So basically, I want to only call some script if the URL does not equal blogs.html
For example, these parameters should NOT call the script:
mydomains.com/blogs
mydomains.com/blogs.html
This parameters should call the script:
mydomains.com/blogs/child-page.html
mydomains.com/blogs/another-page
mydomains.com/blogs.html/testin-page.html
mydomains.com/page.html
mydomains.com
I have attempted something like this, although it does not seem to work since blogs.html and blogs are still within the URL.
if(!document.URL.indexOf("blogs.html") >= 0 && !document.URL.indexOf("blogs") >= 0)
{
other script here
}
Is there any way that I can fix this?
First get the pathname, then use the substring method to get everything after the last "/".
var pathName = window.location.pathname;
var pageName = pathName.substr( pathName.lastIndexOf("/") + 1 );
if( pageName != "blogs.html" && pageName != "blogs" ) {
// do something.
}
if(!document.URL.endsWith("blogs.html"))
{
// code here
}
string has endsWith() methods to accomplish this goal
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString%2FendsWith
or use a regular expression: $
if(!document.URL.search(/(blogs.html)$/) != -1)
// return -1 means a string is not end with blogs.html
{
// code here
}
http://jsfiddle.net/rchMe/
I want to add the the following jQuery to the following pages only.
http://www.mywebsite.com/check-8.asp
http://www.mywebsite.com/edit-8.asp
http://www.mywebsite.com/cart-8.asp
So this means I want to add it where URL string contains either check-8, cart-8 or edit-8.
What is the best way with jQuery or JavaScript?
var text = $('#system td.td-main').html();
if (text != null)
{
var newtext = text.replace("Pris","<div id=\"pricebox\">Pris").replace("mva\)","mva\)</div>");
$('#system td.td-main').html(newtext);
}
Thanks in advance.
if(location.pathname.indexOf('check-8') > 0 || location.pathname.indexOf('cart-8') > 0 || location.pathname.indexOf('edit-8') > 0){
//your code here
}
Or you can use the following:
function testForCheckEditCart() {
var patt = /(check|edit|cart)-8/i;
return patt.test(location.href);
}
If you want a pure JavaScript solution, use the window.location property:
if (window.location.href.match(/(check|cart|edit)-8/).length > 0) {
// do your stuff
}
You can use the string.match method to check if it matches a Regex. You can also factor it out if you need to know which one it is:
var matches = window.location.href.match(/(check|cart|edit)-8/);
if (matches.length > 0) {
var action = matches[1]; // will be check, cart or edit
}