Using || to coalesce first non null value - javascript

Here is a function:
function() {
// if on wordpress site decipher if English or Français by using url path
var lang = '';
var wp_path = document.location.pathname.match(/^\/(en|fr)\//)[0];
if (wp_path == "/en/") {
lang = "Français";}
else if (wp_path == "/fr/") {
lang = "English";
}
// if on ruby site decipher if English or Français by using querySelector on element
var ruby_lang = document.querySelector('.menu--primary a[href*="lang="]').textContent.trim();
// either lang or ruby_lang will be null, assign value to opp_language accordingly
var opp_language = lang || ruby_lang;
return opp_language;
}
In the Chrome JS console this works if I type it line by line:
E.g. on url http://www.example.com/en/
var lang = '';
var wp_path = document.location.pathname.match(/^\/(en|fr)\//)[0];
if (wp_path == "/en/") {
lang = "Français";} // yes NOT English, it's opposite
else if (wp_path == "/fr/") {
lang = "English";
}
Returns Français as expected.
Then, when I'm on a page without a url path containing either en or fr I know that the variable "ruby_lang" will return either English or Français. I have verified this second part of the function works in the console.
So the 3rd part is presumably the problem. My expectation is that at this point, either lang or ruby_lang are set to a truthy value. So:
// either lang or ruby_lang will be null, assign value to opp_language accordingly
var opp_language = lang || ruby_lang;
But instead, whenever I run this function opp_language is undefined.
Does the double bar || syntax behave in a different way than I understand?

If after this line var opp_language = lang || ruby_lang; your variable app_language is undefined this means that both lang and ruby_lang are evaluating to false. If all values in a "coalesce series" evaluate to false the expression will return the last value in the list.
If you go ahead and type in your console right now var a = b || c where b and c are undefined and then log a you will see that it is indeed undefined.
When an element is not found by document.querySelector() your ruby_language will be null or undefined, if you are getting undefined then it most probably is.
So basically make sure your variables are initialized and have default values that don't evaluate to false, I guess.

I got this working but I don't really understand it. I used try and catch which I have never used before. From what I understood, if the variables could not be set they would just be falsy no?
Anyway, this works:
function() {
// if on wordpress site decipher if English or Français by using url path
var lang = '';
try {
var wp_path = document.location.pathname.match(/^\/(en|fr)\//)[0];
if (wp_path == "/en/") {
lang = "Français";}
else if (wp_path == "/fr/") {
lang = "English";
}
} catch (e) {
lang = false;
}
// if on ruby site decipher if English or Français by using querySelector on element
try {
var ruby_lang = document.querySelector('.menu--primary a[href*="lang="]').textContent.trim();
}
catch (e) {
var ruby_lang = false;
}
// either lang or ruby_lang will be null, assign value to opp_language accordingly
var opp_language = lang || ruby_lang;
return opp_language;
}

Related

How to add variable inside google URL in Javascript? I have tried but in Google it shows up meaning of "Undefined"

When I run it shows me the meaning of "Undefined" in Google.
When I run it, it performs a Google search for the word "Undefined".
function search(){
var x = document.getElementById("search").value;
const url = "https://www.google.com/search?q="+ x +"&oq="+ x +"&aqs=chrome..69i57j69i58.1760j0j7&sourceid=chrome&ie=UTF-8";
var win = window.open(url);
}
If the #search field cannot be found document.getElementById() returns undefined, which is used as part of the search query.
You can write a function like this, which will allow you to pass in a value to be searched.
function search(query){
window.open("https://www.google.com/search?q=" + query)
}
Or stick with your code but set a default value in the event that the selector does not return a match
function search(){
let x = document.getElementById("search").value;
if(x){
const url = "https://www.google.com/search?q=" + x
let win = window.open(url);
}
else {
console.log("No elements had the search id")
}
}

Call functions from sources directly in Chrome console?

For a website there is this function under sources with the code:
betSlipView.prototype.stakeOnKeyUp = function(_key) {
var model = ob.slip.getModel(),
defval = ob.cfg.default_bet_amount;
selector = toJqId(["#stake-", _key].join('')),
stake_box = $(selector),
spl = stake_box.val();
if(spl != defval) {
spl = ob.slip.cleanFormatedAmount(spl);
if(spl === '' || isNaN(spl)) {
spl = 0;
$(selector).val('');
}
model.setBetStake(_key, spl);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
} else {
$(selector).val(defval);
model.setBetStake(_key, defval);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
}
//Update bonus amount
try {
var offers = model.getBet(_key, 'offers');
}
catch(err) {
var offers = "";
}
if(offers !== "" && typeof offers['STLWIN'] !== "undefined") {
this._handleAccumulatorBonusElements(_key, offers['STLWIN']);
};
// potential returns for this bet
this.updateTotals();
};
I cannot figure out how to (if possible) call this function directly from the console. Firstly, when I try to write betSlipView in the console, it cannot be found. Consequently if I copy the code to the console to define the function, betSlipView is still not found and if I try to change the function name, there are some names in the function body that cannot be found either. I wish to call this function with certain arguments, is this possible?
The whole code can be found here https://obstatic1.danskespil.dk/static/compressed/js/ob/slip/crunched.pkg.js?ver=0305f181cb96b61490e0fd2adafa3a91

Why doesn't comparing var to "text" work?

I made an if and else statement in Javascript, but I can't get it to work.
This is my code, I hope you people will see whats wrong
var int = "";
function fbLoop (userLoop)
{
int=setInterval(function(){fbCheckloop(userLoop)},1000);
}
function fbCheckloop(userCheck)
{
if(userCheck.login != 'false')
{
window.clearInterval(int);
console.log(userCheck);
fbUpload(userCheck);
}
else
{
$.get("uploadtofb.php", {functie: "checklogin", fotonaam: userCheck.fotonaam}, fbCheckloop);
}
}
The if(userCheck.login != 'false') doesn't work.
The console.log(userCheck); shows this
{"login":"false","fotonaam":"NAME"}
So according to the console log he have to do the else, but he does the if statement.
What did I do wrong?
The userCheck is coming from this:
return json_encode($checklog = array(
'login' => 'false',
'fotonaam' => $_GET['fotonaam']
));
Are you sure that userCheck is a JavaScript object, and not a JSON string that has to be parsed? Your current console log result makes me suspect that it is. What does console.log(typeof userCheck) yield?
If it is, use
userCheck = JSON.parse(userCheck)
if userCheck.login is having boolean value false, use if(userCheck.login != false).
No quotes required around false.

Get attribute value from xml by checking conditions

Following is my xml from where I have to get attribute value:
<R a="1" b="2">
<I attribute1="" attribute2="some text"/>
<I attribute1="" attribute2="some text"/>
<I attribute1="0" attribute2="some text"/>
<I attribute1="0" attribute2="some text"/>
</R>
Here I've to check if attribute1 is not null then I've to get value of attribute2 from I tag.How to do this???
Please help...
UPDATE:
Here's a full X-browser working script that should do the trick. Again, replace the getAttribute('attribute1') by either arguments or return the DOM and take care of the rest. This code might look a bit complicated (it uses closures to be as lightweight as possible) but it should be quite sturdy and safe to use... as long as you don't declare another function called parseXML and you don't call this parseXML prior to it being declared.
var parseXML = (function(w,undefined)
{
'use strict';
var parser,i,ie,parsed;
ie = false;
switch (true)
{
case w.DOMParser !== undefined:
parser = new w.DOMParser();
break;
case new w.ActiveXObject("Microsoft.XMLDOM") !== undefined:
parser = new w.ActiveXObject("Microsoft.XMLDOM");
parser.async = false;
ie = true;
break;
default :
throw new Error('No parser found');
}
return function(xmlString,getTags)
{
var tags,keep = [];
if (ie === true)
{
parser.loadXML(xmlString);
parsed = parser;
}
else
{
parsed = parser.parseFromString(xmlString,'text/xml');
}
tags = parsed.getElementsByTagName(getTags);
for(i=0;i<tags.length;i++)
{
if (tags[i].getAttribute('attribute1') && tags[i].getAttribute('attribute2'))
{
keep.push(tags[i].getAttribute('attribute2'));
}
}
//optional:
keep.push(parsed);//last element of array is the full DOM
return keep;
}
})(this);
var parseResult = parseXML('<r><i attribute1="" attribute2="Ignore This"/><i attribute1="foo" attribute2="got this"/></r>','i');
alert(parseResult[0] || 'nothing');//alerts 'got this' in IE and others
You can parse the XML:
var parser = new DOMParser();
var parsed = parser.parseFromString('<r a="1" b="2"><i v="" x="some text"/><i v="0" x="some important text"/></r>','text/xml');
var iTag = parsed.getElementsByTagName('i');
for (var i=0;i<iTag.length;i++)
{
if (iTag[i].getAttribute('v'))
{
console.log(iTag[i].getAttribute('x'));//do whatever
}
}
This snippet will log some important text, and not some text. That's all there is to it. If you need to store the x values, or return them just declare another variable:
var keep = [];//an array
//change console.log line by:
keep.push(iTag[i].getAttribute('x'));
This is assuming an x property will be set, if that's not always the case, an additional check can easily fix that. The full code will then look like:
function parseXML(xml)
{
'use strict';
var parser,keep,parsed,i,iTag;
parser = new DOMParser();
keep = [];
parsed = parser.parseFromString(xml,'text/xml');//xml is the string
iTag = parsed.getElementsByTagName('i');
for (i=0;i<iTag.length;i++)
{
if (iTag[i].getAttribute('v') && iTag[i].getAttribute('x'))
{
keep.push(iTag[i].getAttribute('x'));
}
}
return keep;//return array
}

javascript to stop specific service

I have the following code in a script.
The problem is That I want to get information of scripts that starts in a specific name and are in a specific startmode.
var e = new Enumerator(GetObject("winmgmts:").InstancesOf("Win32_Service"))
var WSHShell = new ActiveXObject ("WScript.Shell");
var strPrefix = "TTTT";
for(;!e.atEnd(); e.moveNext()){
var Service = e.item();
var strName = Service.Name;
if (strName.substr (0, strPrefix.length) == strPrefix) {
if(Service.StartMode == 'mmManual') {
WScript.Echo("Yes");
}
if(e.StartMode == 'Manual') {
WScript.Echo("Yes");
}
}
}
In the above script I tried to know the start mode but it always return true.
McDowell is right, but note that you can get rid of prefix and start mode checks in your loop if you make them part of the WMI query:
SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'
Using this query, your script could look like this:
var strComputer = ".";
var oWMI = GetObject("winmgmts://" + strComputer + "/root/CIMV2");
var colServices = oWMI.ExecQuery("SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'");
var enumServices = new Enumerator(colServices);
for(; !enumServices.atEnd(); enumServices.moveNext())
{
var oService = enumServices.item();
WScript.Echo(oService.Name);
}
I'm not sure exactly what you're asking, but this...
if(Service.StartMode = 'mmManual')
...will always evaluate to true. You are missing an =. It should be:
if(Service.StartMode == 'mmManual')

Categories

Resources