Chrome extension: String comparison in JavaScript not working - javascript

I am trying to compare two strings using JavaScript, and I am honestly stumped as to why this is not working for me. I've tried using ==, ===, localeCompare(), adding spaces, converting it to lowercase, and nothing is working! Here is my code (from my content script)
var longBrand = byline.innerHTML;
var brand = longBrand.substring(7);
console.log(brand);
if(brand){
console.log("It can read inside this statement");
var lowerBrand = brand.toLowerCase();
console.log(lowerBrand);
if(lowerBrand === "nike" || lowerBrand === " nike" || lowerBrand === " nike"){
console.log("testing");
}
}
The variable brand comes from a substring of longBrand, which is taken from a webpage. The console shows everything is logged except for the last console.log("testing"); and I can't figure out why that is. Console looks like this:
Nike
It can read inside this statement
nike
I've even double checked that typeof brand is a string. I don't know what's going wrong here! Any help would be greatly appreciated!

Well, it works good here. Maybe your variable brand isn't "Nike". Try to do:
brand = brand.trim(); to remove white spaces.
// var longBrand = byline.innerHTML;
// var brand = longBrand.substring(7);
const brand = "Nike"
if(brand){
console.log("It can read inside this statement");
const lowerBrand = brand.toLowerCase();
console.log(lowerBrand);
if(lowerBrand === "nike" || lowerBrand === " nike" || lowerBrand === " nike"){
console.log("testing");
}
}

Related

Compare two variable string in JavaScript

i am trying to compare two strings in javascript. below is my code
var statuss = document.getElementById("status").innerHTML;
//alert(statuss);
var s =statuss.toString();
var ss= "Active";
if (s === "Active"){
alert ('match');
}
else {
alert ('do not match');
}
why am i getting the output " do not match" when it should have been 'match' since when i did
alert ('document.getElementById("status").innerHTML');
i got the output: Active.
So basically both variable should have matched.. why am getting the opposite?
You might want to try the following
var s = statuss.toString().trim();
The most likely explanation is that your HTML also contains whitespace at the beginning and/or end.

how can I get the results of group 1 of a regex match in java script while I can't declare the string?

here is the regex demo
the REGULAR EXPRESSION
getObj\("Frm_Logintoken"\).value = "(.*)";
this the TEST STRING
getObj("Frm_Logintoken").value = "3";
i want to get that number only "3" without quotes
it's in the Group 1 of the matches but i don't know how to get it from that group .
i can't var myString = "something format_abc";
because i am doing this to get the value that i don't know !!
And testing this in console results
var test = /getObj("Frm_Logintoken").value = "(.*)";/g
undefined
console.log(test1);
undefined
undefined
the same question but in a different way and detailed still unanswered
i have tried
getObj\("Frm_Logintoken"\).value = "(.*)";`.match(/getObj\("Frm_Logintoken"\).value = "(.*)";/)[1]
it give me this "(.*)" not the wanted value !!!
some notes
1-that value isn't static
2- i want to make the code works automatic so fetching the line "getObj("Frm_Logintoken").value = "3";"
from the page code manually is unwanted thing.
3- i want to make an auto login script without any User intervention.
4- if you still don't understand the question see the links pls
thanks
You can access group by accessing index of matched value
let str = `getObj("Frm_Logintoken").value = "3";`
let op = str.match(/getObj\("Frm_Logintoken"\).value = "(.*)";/)
console.log(op[1])
you must declare the string first !
so if you are trying to get the value from the current page html code you can just
let str = document.body.innerHTML;
let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
console.log(str.match(pattern)[1]);
and if you are trying to fetch the html string from other page using something like XMLHttpRequest
you can do this
let str = (http.responseText);
the full code :
const http = new XMLHttpRequest();
const url = 'http://page/';
http.open('get', url, false);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function ()
{
if(http.readyState === 4)
{
if(http.status === 200 || http.status == 0)
{
let str = (http.responseText);
let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
let results = str.match(pattern)[1];
console.log(results);
}
}
}
http.send();
Hope you understand and make a Clearer question next time and write your really point of the question and the use of the wanted fix .

understanding usage of eval() to evaluate boolean

I was just going through the code of timer.js HERE. and came across the following lines of code:
var paramList = ['autostart', 'time'];
for (var arg in paramList) {
if (func[paramList[arg]] != undefined) {
eval(paramList[arg] + " = func[paramList[arg]]");
}
};
In the source code its all on one line, but i've made it more readable above , my difficulty is with the usage of eval, I.E. the below line of code:
eval(paramList[arg] + " = func[paramList[arg]]");
now if i add a breakpoint in chrome to the above line and go to the console and paste the line of code i get the following:
true
How come ? lets have a close look at the statement again:
eval(paramList[arg] + " = func[paramList[arg]]");
what is the + doing here ? converting paramList[arg] to a string , in which case eval is being used as follows:
eval("paramList[arg] = func[paramList[arg]]");
?
or is the plus sign being used for concatenation purpose ? (which i think is very unlikely !)
I have read MDN eval(), but still had doubts.
can anybody explain the breakdown of that statement please ?
Thank you.
eval takes a string. What you have:
eval(paramList[arg] + " = func[paramList[arg]]");
The + is just string concatenation.
Is equivalent to:
var code = paramList[arg] + " = func[paramList[arg]]"
eval(code);
So I'd say it should be equivalent to:
global[paramList[arg]] = func[paramList[arg]];
Or, in this particular example (with var paramList = ['autostart', 'time'];)):
if (func['autostart'] != undefined)
autostart = func['autostart'];
if (func['time'] != undefined)
time = func['autostart'];

Can someone help edit Javascript string with both a for loop and the splice command?

I'm writing a script that's going to take some information about the website that you visit. I have copied this small portion of my code that I'm struggling with. This part of the code is supposed check if the visited website is using the www prefix and remove that prefix, then there is another part of the code that I haven't pasted stores the domain name in the variable website.
var website = location.hostname;
document.getElementById("displayBefore").innerHTML = website; //test to see the variable
if (website[0] == 'w' && website[1] == 'w' && website[2] == 'w' && website[3] == '.') {
document.getElementById("displayTrue1").innerHTML = "true"; //test to see if the conditional was met
for (i = 4; i < website.length; i++) {
website[i - 4] = website[i]; //this is not rewriting anything
document.getElementById("displayPos0").innerHTML = website[i]; //test to see if the for loop has run
}
document.getElementById("displayDuring").innerHTML = website; //test to see the variable
website.splice(0, 4); //this is breaking everything after it
document.getElementById("displayAfter").innerHTML = website; //test to see the variable
}
Here is what's actually being displayed when in those tests when I pull it up in a browser:
WebsiteBeforeFix: www.example.com
True1: true
website[i]: m
WebsiteDuringFix: www.example.com
WebsiteAfterFix:
The two parts of the code that aren't working are the following:
website[i - 4] = website[i];
This is supposed to pretty much shift the letters over 4 spaces to the left(eliminating "www.").
website.splice(0,4);
This is actually causing nothing after it to display at all in any of the code that does work. Can anyone tell me what I may be doing wrong?
splice is an array method, not for strings (they're immutable). Make the variable an array to manipulate it using the split method, and join it back together using the join method:
var websiteStr = location.hostname;
var website = websiteStr.split('');
console.log("displayBefore: " + website.join(''));
if (websiteStr.indexOf("www.") === 0) {
console.log("true");
/*for (var i = 4; i < website.length; i++) {
website[i - 4] = website[i];
console.log("displayPos0: " + website[i]);
}*/
console.log("displayDuring: " + website.join(''));
website.splice(0, 4);
console.log("displayAfter: " + website.join(''));
}
Instead of manipulating HTML, you can use console.log to do basic logging at particular points, which will show up in your browser's console. Anyway, it seems that your for loop doesn't do what you want it to -- splice already removes the "www." prefix.
You can also change this:
if (website[0] == 'w' && website[1] == 'w' && website[2] == 'w' && website[3] == '.') {
to this:
if (websiteStr.indexOf("www.") === 0) {
which performs the same thing much more concisely.
With the fixed code, it now displays:
displayBefore: www.google.com
true
displayDuring: www.google.com
displayAfter: google.com

Improve this search engine detecter with javascript

I have the following code which detects which search engine and what search term has been used:
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help!
Have you tried leveraging existing JS URL parsing schemes? It might save you a bunch of time. For example:
http://blog.stevenlevithan.com/archives/parseuri
It's cutting the "h" off because q= was not in the referrer string. So your start variable is -1. Then you add 2 to that to get your searchTerms var with a substring. You need to check for start to be equal to -1 and return.
I also think your "google" string detection is not bulletproof, I would rather do something like this...
var ref = document.referrer;
var pcol = ref.indexOf("://") + 3;
if(ref.indexOf("google.com") == pcol || ref.indexOf("www.google.com") == pcol) {
// It is google
}
One last thing, you should use decodeURIComponent instead of unescape.

Categories