If document URL indexOf - javascript

I have some search page link: www.example.com/search.php?search=search_word, I am tried to make a default search URL. If people only type www.example.com/search.php via the browser, make a default URL as www.example.com/search.php?search=aaa. My code does not work.
<script src="../jquery.js"></script>
<script>
jQuery(document).ready(function(){
var currneturl = document.URL;
if(!document.URL.indexOf('?')){
document.URL = currneturl + '?search=aaa';
}
});
</script>

The .indexOf() method returns -1 if the string is not found, and -1 is a truthy value such that !-1 is false. You need to explicitly test for -1:
if (document.URL.indexOf('?') === -1) {

Related

How to redirect user on another page depending on location using JS/JQuery?

I am trying to write a simple script to redirect users on different pages depending on their location.
Basically, the https://ipapi.co/country/ page is returning a value based on locations, such as "GB" - for the UK. So when the script returns "GB", the user should be redirected to UK.html.
You can notice that in the second condition, I am trying to use an array of countries. If the user is from IT or FR or DE, then I want him redirected to EU.html.
Because I'm a complete beginner, I think something is missing in the following code and I hope you can help me understand what is missing and what would be the correct code to write.
<script type="text/javascript">
$.get('https://ipapi.co/country/', function(country){
console.log(country)
})
if (country = "GB") {
window.location.replace("UK.html");
}
else if (country = ["FR","IT","DE","CH"]) {
window.location.replace("EU.html");
}
else {
window.location.replace("US.html");
}
</script>
Thank you!
change window.location.replace("US.html") to window.location="US.html"
<script type="text/javascript">
$.get('https://ipapi.co/country/', function(country){
console.log(country)
})
if (country === "GB") {
window.location="UK.html";
}
else if (["FR","IT","DE","CH"].indexOf(country )!==-1) {
window.location="EU.html";
}
else {
window.location="US.html";
}
</script>
I will provide a simple solution which does not require jQuery.
One function will make a request to https://ipapi.co/country/.
A second function will perform the redirect depending on the response of the first.
<script type="text/javascript">
const whatCountry = function(){
const xhr = new XMLHttpRequest()
xhr.open("GET", "https://ipapi.co/country/")
xhr.onload = function(){
checkCountryAndRedirect(xhr.response)
}
xhr.send()
}
const checkCountryAndRedirect = function(country){
if(country === "GB"){
window.location.replace("UK.html");
} else if(country === "FR" || country === "IT" || country === "DE" || country === "CH"){
window.location.replace("EU.html")
} else {
window.location.replace("US.html")
}
}
</script>
Once these two functions are defined, you can call the request with whatCountry()
To clarify, the part of your code that checks for country must be part of the callback, as AJAX requests are asynchronous.
The if checks you are doing will always evaluate to true, because a single = indicates that you are assigning the value on the right to country.
The second if statement would be checking whether country was the array ["FR","IT","DE","CH"]. To check whether country was one of those four countries, you can test whether country is equal to each of those countries (not a very clean solution). You can also use switch statements, but I like the indexOf solution suggested above.
EDIT: I have used window.location.replace but window.location = ... would be more suited to your case.

Change div/span content by url addition?

I dont find a solution, so maybe its not possible with jquery?
My plan:
I have some divs like this:
<div>
<span class="en">Hello</span>
<span class="de">Hallo</span>
</div>
<div>
<span class="en">Whats up?</span>
<span class="de">Wie geht´s?</span>
</div>
aso.
So, if my url is just www.domain.com/..., only the "en"-content should be shown. If the url is www.domain.com/de/..., only the "de"-content should be shown. Is this possible with jquery?
You could do something like this:
var url = window.location.href; //Get URL
if (url.includes("/de/")) { //If URL Contains /de/
$('.en').hide();
} else {
$('.de').hide();
}
EDIT:
If you don't want to use includes due to browser support (as FlatLander points out in his answer, includes is ES6), then you can use indexOf:
var url = window.location.href; //Get URL
if (url.indexOf("/de/") !== -1) { //If URL Contains /de/
$('.en').hide();
} else {
$('.de').hide();
}
Cross browser support
includes is not available in all browser so try indexOf
var url = window.location.href;
if (url.indexOf("/de/") !== -1) { //If URL Contains /de/
$('.en').hide();
} else {
$('.de').hide();
}
includes is an es6 feature https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility

Make javascript if statement display html?

I wanted an if statement to show an image or html code depending on the webpage. I got this far and the html table doesn't appear at all (appears blank):
<script type="text/javascript">
<!--
var url = document.location.pathname;
if( document.location.pathname == '/tagged/photos' ){
document.innerHTML('<table><tr> hello </tr> </table>');
}
if( document.location.pathname == '/tagged/news' ){
document.write("<b>This is my news page</b>");
}
//-->
</script>
I'd do it slightly differently
Add both markup to the page, and show/hide as approproate:
<table id="table"><tr> hello </tr></table>
<span id="title"><b>This is my news page</b></span>
<script type="text/javascript">
$(function(){
var url = document.location.pathname;
if( url == '/tagged/photos' ){
$('#title').hide();
$('#table').show();
}
if( url == '/tagged/news' )
{
$('#title').show();
$('#table').hide();
}
})
</script>
I have assumed you have JQuery since it is tagged
You're using document.innerHTML, which doesn't exist. At the very least, you need to get a proper element:
document.documentElement.innerHTML = 'some HTML';
Setting aside everything else that's wrong with this approach, I'm not sure, why would you use document.write() in one branch and someElement.innerHTML in the other.
I'd suggest the following approach:
function pagePopulate() {
// you're looking at the pathname, use a sensible (meaningful) variable-name:
var pagePath = document.location.pathname,
// this is a map, of the relationship between page and content:
pathToContent = {
// pagename : html
'photos': '<table><tbody><tr><td>photos page</td></tr></tbody></table>',
'news': '<b>This is the news page</b>'
},
// getting a reference to the <body> element:
body = document.querySelector('body');
// setting the innerHTML of the <body>,
// if pagePath = 'tagged/photos', splitting with '/' would return:
// ['tagged','photos'], calling 'pop()' returns the last element of the array
// 'photos', which returns that string to the square brackets, resulting in:
// pathToContent['photos'], which would yield the '<table>...</table>' HTML.
// if that call resulted in an undefined, or falsey, value, then the default
// (the string *after* the '||' would be used instead:
body.innerHTML = pathToContent[pagePath.split('/').pop()] || '<h2>Something went wrong</h2><img src="http://blog.stackoverflow.com/wp-content/uploads/error-lolcat-problemz.jpg" />';
}
// calling the function:
pagePopulate();
References:
|| (logical 'or' operator).
Array.prototype.pop().
document.querySelector().
String.prototype.split().

Get servlet context in javascript

In my jsp I use <%String base = (String)application.getAttribute("base");%>
I tried to use 'base' in javascript but not work. Below is my javascript:
<script>
var newBase = <%=base%>;
</script>
Can anyone help me to solve this?Thanks
This is the eplanation www.w3schools.com give for location object property pathname:
pathname: Sets or returns the path name of a URL
In our case the javascript file wich is in your context.
The first element is that pathname is the context
So you split the attribute (see the split method in javascript String) and return it.
This should do.
<script language='javascript'>
function servletContext() {
var sc = window.location.pathname.split( '/' );
return "/"+sc[1];
}
</script>
You can rather try it out like this ,
set the value to the hidden field ,
input type="hidden" id="hidVal" name="txt2" value="${base}"/>
And in your java script ,
<script>
var x = document.getElementById('hidVal').value;
alert(x);
</script>
Update :
var newBase = '<%=base%>';
You are missing the quotes to treat the value as string .
Hope this helps !!

Regexp JS from referrer

I need to check if a referrer has word "profile" i need to put profile/(.*?) in a var. How can I do it in js?
<script type="text/javascript">
var ref = document.referrer;
if( ~ref.indexOf("profile") ) {
alert('coincidence found!');
}
</script>
<script>
var str="Is this all there is?";
var patt1=/[^a-h]/g;
document.write(str.match(patt1));
</script>
Result :I,s, ,t,i,s, ,l,l, ,t,r, ,i,s,?
check link The [^abc] expression is used to find any character not between the brackets.
and this tooo link
var ref = document.referrer;
ref.match(/(?:profile).+/,(match)=> {
console.log(match)
})

Categories